获取滚动条的偏移量
document.documentElement.scrollTop
IE浏览器一般用这个值
document.body.scrollTop
为了兼容,我们一般通过下面代码获取滚动条的偏移量:
scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
html结构:
<template>
<div class="param-bar" :class="{ 'is_fixed': isFixed }">
<div class="container">
<div class="pro-title">
MI8
</div>
<div class="pro-params">
<a href="javascript:;">概述</a><span>|</span>
<a href="javascript:;">参数</a><span>|</span>
<a href="javascript:;">评价</a>
<slot name="buy"></slot>
</div>
</div>
</div>
</template>
sass:
<style lang="scss" scoped>
@import '../assets/config.scss';
@import '../assets/mixin.scss';
.param-bar{
background: $colorG;
box-shadow: 0 5px 5px $colorE;
width: 100%;
height: 70px;
line-height: 70px;
border-top: 1px solid $colorH;
&.is_fixed{
position: fixed;
top: 0
}
.container{
@include flex();
.pro-title{
font-size: $fontH;
color: $colorB;
font-weight: bold;
}
.pro-params{
font-size: $fontJ;
a{
color: $colorC;
}
span{
margin: 0 10px;
}
}
}
}
</style>
js:
<script>
export default {
name: 'param-bar',
data () {
return {
isFixed: false
}
},
mounted () {
window.addEventListener('scroll', this.initHeight)
},
methods: {
initHeight () {
console.log(111)
const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
this.isFixed = scrollTop > 152 ? true : false
}
},
// 页面关闭就销毁initHeight,不然还会在其他页面加载浪费资源
destroyed () {
window.removeEventListener('scroll', this.initHeight, false)
}
}
</script>
要注意的是:
param-bar动态绑定
mounted时候调用js原生的addEventListener,监听scroll事件,并且调用this.initHeight方法:
initHeight方法判断是否滚动到需要吸顶的位置,到了就修改isFixed的值为true
最喜耀注意的是,一定要在destroyed生命周期钩子里销毁这个事件监听,不然在其他页面还会调用,浪费资源:
我们看一下如果不销毁,会怎么样:
发现即使退出了产品页面回到首页,还是会叫用scroll事件监听。
所以我们在destroyed里面把这个scroll事件监听销毁掉:
现在看看效果:
还有一个要注意的就是一定要给param-bar添加width:100%,让它撑开到全部宽度,不然一旦动态加上position:fixed就没有宽度了就不会居中了