代码
<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>
</template>
<script>
export default {
name: "home",
data() {
return {
offsetTop: 0,
offsetHeight: 0,
headerFixed: 0
};
},
mounted() {
this.$nextTick(() => {
let header = this.$refs.header;
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;
height: 80px;
line-height: 80px;
}
</style>