1, requires effect
2, Implementation
(1) native js achieve
document.addEventListener('scroll', function (event) { var scrollDamo = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop; if (scrollDamo >= 350) { // 触发的位置 document.getElementsByClassName('cont-info-kc')[0].style.cssText = 'position:fixed;'; } else { document.getElementsByClassName('cont-info-kc')[0].style.cssText = 'position:static;'; } });
html
<div class="cont-info-kc"></div>
(2) vue achieve
<div style="height:16px;background:#F4F4F4" id='testNavBar'></div> <div id="cont-info-kc" :class='{ fixedNavbar: isfixTab }'> <ul> <li :class="period==-1 ? 'secactive': ''" @click.stop="getsetion(-1)">全部</li> <li :class="period==155 ? 'secactive': ''" @click.stop="getsetion(155)"Li<>Li</Good> :class="period==156 ? 'secactive': ''" @click.stop="getsetion(156)">晴天</li> <li :class="period==157 ? 'secactive': ''" @click.stop="getsetion(157)">需要</li> </ul> <a @click.stop="moreClick" style="line-height:50px;" v-show="!tongyongIsshow">更多</a> </div>
data () { return { isfixTab: false } }, methods: { // first get id from the top of the page scrolling distance and distance of each of the elements testNavBar // compare their size to determine whether to add fixedNavbar style handleTab () { var scrollTop = window.pageYOffset document.documentElement.scrollTop || || document.body.scrollTop var the offsetTop = document.querySelector ( '# testNavBar' ) .offsetTop scrollTop > offsetTop ? this.isfixTab = true : this.isfixTab = false } }, // listen for page scrolling mounted () { window.addEventListener('scroll', this.handleTab, true) }, // clear when listening to scroll left beforeRouteLeave (to, from, next) { window.removeEventListener('scroll', this.handleTab, true) next() }
.fixedNavbar{ position: fixed; top: 2.25rem; left: 0; width: 100%; border-top: 0.05rem solid #f5f5f5; border-bottom: 0.05rem solid #f5f5f5; background: #f5f5f5; }