原理:判断html标签的页面垂直位置scrollTop与商品展示各区域向上卷曲的offsetTop距离,让电梯导航的盒子出现。
当窗口滚动条滚动的时候,到达楼层区域,电梯导航的标签附带高亮效果。
一、检测页面滚动的距离:
//给 window对象或者 document 对象 注册 scroll 事件,使用 scrollTop 属性获得滚动距离。
document.addEventListener('scroll', function () {
console.log(document.documentElement.scrollTop)
})
二、offsetTop :获取对象相对于版面或由offsetTop属性指定的父坐标的计算顶端位置
- offsetTop:元素到offsetParent顶部的距离
- offsetParent:距离元素最近的一个具有定位的祖宗元素(relative,absolute,fixed),若祖宗都不符合条件,offsetParent为body。如下图所示:获取child的offsetTop,图1的offsetParent为father,图2的offsetParent为body。
三、右侧的电梯导航跟随滚动距离进行调整,elevator导航的自定义名称与各楼层展示区域的类名有进行关联。
//1.目标:当页面滚动大于banner区域的时候,显示右边电梯导航
const elevator = document.querySelector('.xtx-elevator')
// banner区域距离窗口顶部的距离
const entryTop = document.querySelector('.xtx_entry').offsetTop
window.addEventListener('scroll', function () {
const n = document.documentElement.scrollTop
elevator.style.opacity = n > entryTop ? 1 : 0
})
//当点击返回顶部按钮的时候,页面返回顶部
const backTop = document.querySelector('#backTop')
backTop.addEventListener('click', function () {
//window.scrollTo(X坐标,Y坐标)
window.scrollTo(0, 0)
})
// 2. 需求:点击返回按钮,页面会返回顶部
// 将 document.documentElement.scrollTop 的值 设置为 0
const backTop = document.querySelector('#backTop')
backTop.addEventListener('click', function () {
document.documentElement.scrollTop = 0
})
// 3. 需求:点击不同的模块,页面可以自动跳转不同的位置,并设置高亮效果
elevator.addEventListener('click', function (e) {
if (e.target.tagName === 'A' && !e.target.id) {
// 判断选中的导航是否有active高亮,先移除,后给点击的这一个添加
const activeObj = document.querySelector('.xtx-elevator-list a.active')
activeObj && activeObj.classList.remove('active')
e.target.classList.add('active')
// 点击 a 的时候 获取 a 标签的 自定义属性值,dataName 关联 对应的 html 标签对象
const dataName = e.target.dataset.name
const obj = document.querySelector(`.xtx_goods_${dataName}`)
// 获取这个元素离页面顶部的距离
const objTop = obj.offsetTop
// 将这个距离赋值给html页面滚动的scrollTop
document.documentElement.scrollTop = objTop
}
})
// 4.需求 页面滚动到商品楼层位置,电梯导航小盒子对应模块自动处于选中状态
// 获取楼层离页面顶部的距离
const newTop = document.querySelector('.xtx_goods_new').offsetTop // 新鲜好物顶部距离
const popularTop = document.querySelector('.xtx_goods_popular').offsetTop // 人气推荐
const brandTop = document.querySelector('.xtx_goods_brand').offsetTop // 热门品牌
const topicTop = document.querySelector('.xtx_goods_topic').offsetTop // 最新专题
document.addEventListener('scroll', function () {
const activeObj = document.querySelector('.xtx-elevator-list a.active')
//如有高亮,先移除所有高亮。滚动到哪个区域,给哪个区域加高亮效果
activeObj && activeObj.classList.remove('active')
// 需要判断是否滚动到对应的位置
const n = document.documentElement.scrollTop
if (n >= newTop && n < popularTop) {
document.querySelector('[data-name="new"]').classList.add('active')
} else if (n >= popularTop && n < brandTop) {
document.querySelector('[data-name="popular"]').classList.add('active')
} else if (n >= brandTop && n < topicTop) {
document.querySelector('[data-name="brand"]').classList.add('active')
} else if (n >= topicTop) {
document.querySelector('[data-name="topic"]').classList.add('active')
}
})