①監聽頁面滾動
在生命周期mounted
中進行監聽滾動:
mounted () {
window.addEventListener('scroll', this.scrollToTop)
},
在方法中定義監聽滾動執行的方法:
scrollToTop() {
var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
console.log(scrollTop)
},
記得在離開當前路由解綁scroll事件
beforeRouteLeave(to, form, next){
window.removeEventListener('scroll',this.scrollToTop);
next();
}
②監聽某元素滾動
需要監聽的這個元素需要擁有固定的高度
vue組件中:
<div class="read-con" @scroll="scrollEvent" >
</div>
在方法中定義scrolldiv,是監聽class為read-con滾動以后需要執行的方法
scrollEvent () {
let _this = this
let read = _this.$el.querySelector('#read')
console.log(read.scrollToTop)
},
③ 獲取各個元素高度
獲取具體一個元素的真實高度:
使用scrollHeight的時候,如果scrollHeight小於offsetHeight的時候,高度就是offsetHeight,只有超過offsetHeight的時候才是scrollHeight的高度,不管隱藏不隱藏內容
// 文檔高度
let docHeight = document.querySelector('.page').scrollHeight;
獲取窗口高度:
// 窗口高度
let winHeight = document.body.offsetHeight;