vue js手機端滑到某一個位置時固定位置顯示


1、HTML

 <div id="searchBar">
    <ul class="items_filter" :class="searchBarFixed == true ? 'isFixed' :''">
    <li><span class="all">綜合</span></li>
    <li><span class="all">綜合2</span></li>
    <li><span class="all">綜合3</span></li>
    <li><span class="all">綜合4</span></li>
    <li><span class="all">綜合5</span></li>
</ul>
</div>

 

2、data定義

data() {
    return {
      searchBarFixed:false,
    };
  },

3、在mounted鈎子中給window添加一個滾動滾動監聽事件

mounted() {
    window.addEventListener('scroll', this.handleScroll)
  },

4、然后在方法中,添加handleScroll方法

methods: {
    handleScroll () {
      var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
      var offsetTop = document.querySelector('#searchBar').offsetTop
      if (scrollTop > offsetTop) {
        this.searchBarFixed = true
      } else {
        this.searchBarFixed = false
      }
      // console.log(scrollTop,offsetTop)
    },
}

5、添加固定css

.isFixed{
    position:fixed;
}

6,其他的css 根據自己的需求去完成,寫在  items_filter  里面即可

最后,在離開頁面是需要銷毀這個監聽事件:

destroyed () {
    window.removeEventListener('scroll', this.handleScroll)
  },

圖1為不固定,隨頁面的滑動而滾動

圖2為滑動到一定位置時把篩選條件固定在上面

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM