vue中实现元素吸顶效果
作者:互联网
效果图:
注意:窗口会抖动,体验不是很好,后期再优化
代码实现:
<template>
<div>
<div style="height: 100px;"></div>
<div
style="width:100px;height:100px;margin-left:30px;border:1px solid red;color:black"
:class="{isFixed:isFixed}"
>scrollTop:{{scrollTop}}</div>
<div style="height: 1000px;"></div>
</div>
</template>
<script>
export default {
data() {
return {
isFixed: false,
scrollTop: ""
};
},
mounted() {
window.addEventListener("scroll", this.handleScroll);
},
methods: {
handleScroll() {
this.scrollTop =
window.pageYOffset ||
document.documentElement.scrollTop ||
document.body.scrollTop;
if (this.scrollTop >= 100) {
this.isFixed = true;
} else {
this.isFixed = false;
}
}
},
destroyed() {
window.removeEventListener("scroll", this.handleScroll);
}
};
</script>
<style lang="scss" scope>
.isFixed {
position: fixed;
top: 0;
background-color: yellow;
z-index: 999;
}
</style>
标签:vue,false,handleScroll,元素,isFixed,window,scrollTop,document,吸顶 来源: https://blog.csdn.net/qq_40323256/article/details/116348405