<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Vue实现导航栏吸顶效果</title>
</head>
<body>
<script src="static/js/vue.js"></script>
<style>
body {
margin: 0;
}
#app {
height: 2000px;
margin: 0 auto;
background-color: #eeeeee;
}
.nav {
width: 100%;
height: 30px;
background-color: #666666;
}
.fix-nav {
position: fixed;
top: 0;
z-index: 999;
}
</style>
<div id="app">
<div id="nav" class="nav" :class="{'fix-nav': navBarFixed}"></div>
</div>
<script>
const app = new Vue({
el: "#app",
data() {
return {
navBarFixed: false,
};
},
mounted() {
window.addEventListener("scroll", this.watchScroll);
},
destroyed() {
window.removeEventListener("scroll", this.watchScroll);
},
methods: {
watchScroll() {
var scrollTop =
window.pageYOffset ||
document.documentElement.scrollTop ||
document.body.scrollTop;
var offsetTop = document.querySelector("#nav").offsetHeight;
console.log("scrollTop=>", scrollTop, " offsetTop=>", offsetTop);
if (scrollTop > offsetTop) {
this.navBarFixed = true;
} else {
this.navBarFixed = false;
}
},
},
});
</script>
</body>
</html>
参考
Vue 事件监听实现导航栏吸顶效果(页面滚动后定位)