1、需要效果
2、实现方法
(1)原生js实现
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实现
<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 :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: { // 先分别获得id为testNavBar的元素距离顶部的距离和页面滚动的距离 // 比较他们的大小来确定是否添加fixedNavbar样式 handleTab() { var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop var offsetTop = document.querySelector('#testNavBar').offsetTop scrollTop > offsetTop ? this.isfixTab = true : this.isfixTab = false } }, // 监听页面滚动 mounted () { window.addEventListener('scroll', this.handleTab, true) }, //离开时清除滚动监听 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; }