1.在 mounted 生命周期函数注册滚动条事件
mounted() {
window.addEventListener('scroll', this.windowScroll)
}
2.在 methods 方法里使用
methods: {
windowScroll() {
// 滚动条距离页面顶部的距离
// 以下写法原生兼容
let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
console.log(scrollTop);
}
}
3.实例销毁之前,解绑事件
beforeDestroy() {
window.removeEventListener('scroll', this.windowScroll)
}
获取总高度
var viewportSize = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
console.log(viewportSize)
[JS如何判断滚动条是否滚到底部]
判断滚动条到底部,需要用到DOM的三个属性值,即scrollTop、clientHeight、scrollHeight。
scrollTop为滚动条在Y轴上的滚动距离。
clientHeight为内容可视区域的高度。
scrollHeight为内容可视区域的高度加上溢出(滚动)的距离。
从这个三个属性的介绍就可以看出来,滚动条到底部的条件即为scrollTop + clientHeight == scrollHeight。
代码如下(兼容不同的浏览器)。
<pre style="overflow: auto; margin-top: 0px; margin-bottom: 0px;">
let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
let clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
let scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
避免没有数据的时候 重复执行 scrollHeight > clientHeight </pre>
<pre style="overflow: auto; margin-top: 0px; margin-bottom: 0px;">if(scrollHeight > clientHeight && scrollTop + clientHeight === scrollHeight) {
this.loadmore();
}</pre>
加这个就能显示了
window.onresize = () => {
return (() => {
})()
}
网友评论