<!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>
参考