Open david2tdw opened 4 years ago
<html> <head> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <style> body { height: 130vh; } .search-bar { overflow: hidden; } .search-bar .is-fixed { position: fixed; top: 0; background-color: #fff; z-index: 999; } ul { display: flex; width: 100%; height: 40px; line-height: 40px; list-style: none; /* 去除ul的默认样式 */ padding: 0px; /* 去除ul的默认样式 */ margin: 0px; /* 去除ul的默认样式 */ } ul li { font-size: 1rem; text-align: center; flex: 1; border-bottom: 1px solid #ddd; } </style> </head> <body> <div id="app"> <div>img1<br />img1<br />img1<br />img1<br />img1<br />img1<br /></div> <div class="search-bar"> <ul :class="searchBarFixed === true ? 'is-fixed': ''"> <li>区域</li> <li>价格</li> <li>房型</li> <li>更多</li> </ul> </div> <div> content<br /> content<br /> content<br /> content<br /> content<br /> content<br /> content<br /> content<br /> content<br /> content<br /> </div> </div> <script> var app = new Vue({ el: '#app', data: { searchBarFixed: false }, mounted() { window.addEventListener('scroll', this.handleScroll) }, methods: { handleScroll() { // scrollTop: 滚动后,顶端被隐藏的高度 // offsetTop: 滚动条顶部距离窗口顶部的高度 // 隐藏的高度 > 距离窗口顶部的高度,则表示element已经到达顶部。 let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop let offsetTop = document.querySelector('.search-bar').offsetTop console.log('scrollTop:' + scrollTop, 'offsetTop:' + offsetTop) this.searchBarFixed = scrollTop > offsetTop } }, computed: {}, destroyed() { window.removeEventListener('scroll', this.handleScroll) } }) </script> </body> </html>
vue监听滚动事件 实现某元素吸顶或者固定位置显示
vue监听滚动事件 实现某元素吸顶或者固定位置显示