Home > Article > Web Front-end > Detailed explanation of how vue listens to scroll events and displays an element at the top or at a fixed position
This article mainly introduces in detail how vue implements ceiling or fixed position display of certain elements and monitors scrolling events. It has certain reference value. Interested friends can refer to it. I hope it can help you.
Recently I wrote a VUE web app project, which needs to achieve the ceiling effect of a certain part. That is, when the page slides up and reaches this part, this part is fixed and displayed at the top.
1. Listen for scroll events
Use VUE to write a scrollTop that prints the current scrollTop on the console.
First, add a scroll to the window in the mounted hook Listen to the event,
mounted () { window.addEventListener('scroll', this.handleScroll) },
Then in the method, add this handleScroll method
handleScroll () { var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop console.log(scrollTop) },
The console prints the result:
2. Listening element The distance to the top and determine if the scrolling distance is greater than the distance from the element to the top, set searchBar to true, otherwise it is false
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 } },
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. If searchBar is true, apply this isFixed style
<p class="searchBar" id="searchBar"> <ul :class="searchBarFixed == true ? 'isFixed' :''"> <li>区域<i class="iconfont icon-jiantouxia"></i></li> <li>价格<i class="iconfont icon-jiantouxia"></i></li> <li>房型<i class="iconfont icon-jiantouxia"></i></li> <li>更多<i class="iconfont icon-jiantouxia"></i></li> </ul> </p>
The fixed result:
Note that if you leave the page, you need to remove this monitored event, otherwise an error will be reported.
destroyed () { window.removeEventListener('scroll', this.handleScroll) },
Related recommendations:
Example sharing on how to implement navigation bar ceiling operation using JavaScript
js implements navigation bar ceiling operation Top effect
Problems in implementing tab ceiling using react.js
The above is the detailed content of Detailed explanation of how vue listens to scroll events and displays an element at the top or at a fixed position. For more information, please follow other related articles on the PHP Chinese website!