一.HTML
用样式控制,如果isFixed 等于true,将内容固定到顶部
<div :class="isFixed ? 'is-fixed' : 'txt'" ref="fixedName">
到顶就被吸住啦
</div>
二.CSS
//不吸顶
.txt{
font-size: 30px;
font-weight: 500;
color: #222222;
line-height: 60px;
text-align: center;
}
//吸顶
.is-fixed {
position: fixed;
top: 0;
z-index: 100;
width: 335px;
left: 20px;
background-color: #FFFFFF;
padding: 15px;
box-sizing: border-box;
font-size: 30px;
font-weight: 500;
color: #222222;
line-height: 60px;
text-align: center;
}
三.JS
1.在onMounted生命周期中监听页面的滚动事件
onMounted(() => {
window.addEventListener('scroll', handleScroll);
})
2.在onUnmounted生命周期中卸载监听事件
onUnmounted(()=>{
window.removeEventListener('scroll', handleScroll);
})
3.首先获取页面滚动的距离,如果页面滚动的距离大于吸顶元素距离页面顶部的距离,就展示使吸顶元素的isFixed为true,即实现吸顶功能。
const handleScroll = () => {
let scrollTop =window.pageYOffset ||document.documentElement.scrollTop ||
document.body.scrollTop;
isFixed.value =scrollTop > proxy.$refs.fixedName.getBoundingClientRect().top ? true
:false;
}
以上代码就能实现吸顶效果。