要实现的功能:实现选择栏置顶之后 选择栏本身背景颜色等属性
这块圈红的这个ul ,现在没有背景色,li 的背景色是白色
现在想要实现以下效果,即黏在顶部时,ul 背景改为白色,li 背景改为会一点的颜色
实现方法:
1、监听scroll滚轮事件
2、获取目标元素位置
3、到达指定位置触发回调
mounted () {
this.stckyChange()
},
methods: {
stckyChange () {
this.callback = function () {
let targetNode = document.querySelector(".classify")
let ul = document.querySelector(".ul")
let li = document.querySelectorAll(".li")
if (targetNode.getBoundingClientRect().top === 28) {
ul.style.background = "#fff"
for (let item of li) {
item.style.background = '#f2f2f2 '
item.style.marginTop = '10px '
item.style.marginBottom = '10px '
}
} else {
ul.style.background = ""
for (let item of li) {
item.style.background = '#fff '
item.style.marginTop = '0px '
item.style.marginBottom = '0px '
}
}
}
window.addEventListener("scroll", this.callback)
}
},
beforeDestroy () {
window.removeEventListener("scroll", this.callback)
}
但是会影响性能吧...一直监听滚轮...
还有一种方式 IntersectionObserver试一下