html
如果isFixed为true,实现吸顶,此处通过ref获取吸顶元素
<div :class="isFixed ? 'is-fixed' : 'title'" ref="fixedName">
文章标题
</div>
css
//不吸顶
.title {
font-size: 30px;
font-weight: 500;
color: #222222;
line-height: 60px;
text-align: center;
}
//吸顶
.is-fixed {
position: fixed;
top: 0;
z-index: 100;
font-size: 30px;
font-weight: 500;
color: #222222;
line-height: 80px;
text-align: center;
width: 100%;
height: 80px;
background-color: #fff;
}
vue
首先在onMounted生命周期中监听页面的滚动事件
onMounted(() => {
window.addEventListener('scroll', handleScroll);
});
在onUnmounted生命周期中卸载监听事件
onUnmounted(() => {
window.removeEventListener('scroll', handleScroll);
});
首先得到页面滚动的距离,如果页面滚动的距离大于吸顶元素距离页面顶部的距离,就展示使吸顶元素的isFixed为true,即实现吸顶功能。
const handleScroll = () => {
let scrollTop =
window.pageYOffset ||
document.documentElement.scrollTop ||
document.body.scrollTop;
isFixed.value =
scrollTop > fixedName.value.getBoundingClientRect().top ? true : false;
};