Vue3实现吸顶效果
步骤1 静态样式编写
定义需要实现吸顶效果的导航容器,并在容器中定义吸顶与非吸顶时的类名,以及对应的css样式在这里插入代码片
html
<div :class="isFixed ? 'isfixed' : 'title'" ref="fixedName">
文章标题
</div>
css
//不吸顶
.title {
font-size: 30px;
font-weight: 500;
color: #222222;
line-height: 60px;
text-align: center;
}
//吸顶
.isfixed {
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;
}
步骤2 vue判断是否吸顶
2.1 首先在onMounted生命周期中监听页面的滚动事件
onMounted(() => {
window.addEventListener('scroll', handleScroll);
});
2.2 在onUnmounted生命周期中卸载监听事件
onUnmounted(() => {
window.removeEventListener('scroll', handleScroll);
});
2.3首先得到页面滚动的距离,如果页面滚动的距离大于吸顶元素距离页面顶部的距离,就展示使吸顶元素的isFixed为true,即实现吸顶功能。
const handleScroll = () => {
let scrollTop =
window.pageYOffset ||
document.documentElement.scrollTop ||
document.body.scrollTop;
isFixed.value =
scrollTop > fixedName.value.getBoundingClientRect().top ? true : false;
};
如果本文章对你有帮助,请点个赞吧!