思路:
1、判断当前页面的滚动高度大于某个值时触发吸顶行为
2、样式 position: fixed; top: 0;width: 100%;,注意宽一定要设置100%,确保横向撑开
3、离开当前页面销毁destroyed 滚动事件
<template>
<div class="nav-bar" :class="{ is_fixed: isFixed }">
<div class="container">
<div class="pro-title">
小米8
</div>
</div>
</div>
</template>
<script>
// @ is an alias to /src
export default {
name: 'nav-bar',
data() {
return {
isFixed: false,
};
},
components: {},
mounted() {
window.addEventListener('scroll', this.initHeight);
},
methods: {
initHeight() {
let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
this.isFixed = scrollTop > 152 ? true : false;
},
// 当离开当前页面时会自动销毁this.initHeight,
destroyed() {
window.removeEventListener('scroll', this.initHeight, false);
},
},
};
</script>
<style lang="scss">
.nav-bar {
height: 70px;
line-height: 70px;
border-top: 1px solid $colorH;
background-color: #fff;
&.is_fixed {
position: fixed;
top: 0;
width: 100%;
box-shadow: 0 5px 5px #ccc;
}
}
</style>
网友评论