使用到的知识点
// 获取吸顶元素的dom
let header = this.$refs.header;
// 吸顶元素到top的距离
this.offsetTop = header.offsetTop;
// 元素自身的高度
this.offsetHeight = header.offsetHeight;
// 监听滚动条
window.addEventListener("scroll", this.handleScroll);
// 得到页面滚动的距离,兼容写法
let scrollTop =
window.pageYOffset ||
document.documentElement.scrollTop ||
document.body.scrollTop;
// 判断页面滚动的距离是否大于吸顶元素的位置
this.headerFixed = scrollTop > this.offsetTop - this.offsetHeight;
具体实现
<template>
<div class="home">
<div ref="header" class="header-bg" :class="headerFixed?'issFixed':''">Header</div>
<div style="height: 500px">111</div>
<div style="height: 300px">222</div>
<div>333</div>
</div>
</template>
<script>
export default {
name: "home",
data() {
return {
offsetTop: 0,
offsetHeight: 0,
headerFixed: 0
};
},
mounted() {
this.$nextTick(() => {
// 获取吸顶元素的dom
let header = this.$refs.header;
// 吸顶元素到top的距离
this.offsetTop = header.offsetTop;
// 元素自身的高度
this.offsetHeight = header.offsetHeight;
// 监听滚动条
window.addEventListener("scroll", this.handleScroll);
});
},
destroyed() {
window.removeEventListener('scroll', this.handleScroll);
},
methods: {
handleScroll() {
// 得到页面滚动的距离,兼容写法
let scrollTop =
window.pageYOffset ||
document.documentElement.scrollTop ||
document.body.scrollTop;
// 判断页面滚动的距离是否大于吸顶元素的位置
this.headerFixed = scrollTop > this.offsetTop - this.offsetHeight;
}
}
};
</script>
<style>
.issFixed {
position: fixed;
top: 0px;
left: 0px;
right: 0px;
z-index: 4;
}
.header-bg {
font-size: 30px;
background-color: red;
}
</style>
网友评论