gogoWebsite

vue's scroll event to realize that an element can be displayed in a fixed position or on top of it.

Updated to 6 hours ago

Recently wrote a VUE web app project, need to realize the effect of a certain part of the ceiling. That is, when the page slides up and just reaches the part, the part, fixed in the top display.



1、Listen to scrolling events

Write a VUE to print the current scrollTop on the console.

First, add a scroll scroll listener event to the window in the mounted hook.

mounted () {
  ('scroll', this.handleScroll)
},
Then in the methods, add this handleScroll method

handleScroll () {
  var scrollTop =  ||  || 
  (scrollTop)
},

The console prints the results:


2、Listen to the distance of the element to the top and determine the distance of the scroll if it is greater than the distance of the element to the top, set searchBar to true, otherwise it is false.

handleScroll () {
  var scrollTop =  ||  || 
  var offsetTop = ('#searchBar').offsetTop
  if (scrollTop > offsetTop) {
    this.searchBarFixed = true
  } else {
    this.searchBarFixed = false
  }
},

First write a style that fixes the element to the top, isFixed (less writing)

.searchBar{
  .isFixed{
    position:fixed;
    background-color:#Fff;
    top:0;
    z-index:999;
  }
  ul {
    WIDTH:100%;
    height: 40px;
    line-height: 40px;
    display: flex;
    li {
      font-size: 0.8rem;
      text-align: center;
      flex: 1;
      i {
        font-size: 0.9rem;
        padding-left: 5px;
        color: #ccc;
      }
    }
    border-bottom: 1px solid #ddd;
  }
}

Then bind the class of the element that needs to be fixed to searchBar and apply the isFixed style if searchBar is true.

<div class="searchBar" id="searchBar">
  <ul :class="searchBarFixed == true ? 'isFixed' :''">
    <li>shore<i class="iconfont icon-jiantouxia"></i></li>
    <li>prices<i class="iconfont icon-jiantouxia"></i></li>
    <li>room type<i class="iconfont icon-jiantouxia"></i></li>
    <li>more<i class="iconfont icon-jiantouxia"></i></li>
  </ul>
</div>

Results after fixation:



Note that if you leave the page you need to remove the event you are listening to, otherwise you will get an error.

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