原生js监听页面滚动事件

我们在做项目时不免会遇到列表,列表中会有分页的请求。

在移动端的列表的加载中,当然如果使用ui框架就另当别论。

这次在做vue移动端的项目时有一个场景是列表上拉加载数据,这种情况肯定是在mounted中给window加上一个滚动监听,

记住这里要提前定义好this如果你有用到this的话,因为监听也算是异步操作,没有提前定义的话会报错。

mounted () {
    this.initList()
    var that = this
    window.addEventListener("scroll", function () {
        if(document.body.scrollHeight <= window.screen.height + document.body.scrollTop){
            if (that.noMore) {
                return
            }
            if (that.initOver) {
                that.initList()
            }
        }
    })
},

当页面滚动到底部即程序走到if判断中执行数据请求。

这里我在做项目的过程中有多次用到滚动监听,有意思的是有的地方成功了有的地方失败了。

原因是不同浏览器获取页面滚动距离的方法不一样。

总结了以下三种

(window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop)

虽然不知道分别对应什么浏览器但是只要向上面的代码一样直接写上去就ok了,函数会找有值的那个进行计算。

还有

在你从列表页跳转到写一页的时候,上一个列表页的页面滚动监听事件还是存在的,当你在下一个页面拉到底部的时候还会继续监听上一个页面的滚动监听。

那么既然在离开页面后依然存在那我们就在离开的时候这个监听事件去掉就行了。

在beforeDestroy中通过个removeEventListener这个方法去掉

beforeDestroy(){
  var that = this
  window.removeEventListener('scroll', that.scroll);//监听页面滚动事件
},

这里我们要封装一下滚动到底部触发的方法。在method中

methods: {
    scroll: function () {
        var that = this
        if (document.body.scrollHeight <= window.screen.height + document.body.scrollTop) {
            if (that.noMore) {
                return
            }
            if (that.initOver) {
                that.init(2)
            }
        }
    },
}

那么mounted中的滚动监听就要写成

mounted: function () {
  this.init(0)
  var that = this
  window.addEventListener("scroll", that.scroll)
},

 removeEventListener后面跟的应该是函数名不能加括号(我也不知道为什么)但是直接写函数却是可以的

猜你喜欢

转载自blog.csdn.net/qq_40816649/article/details/86512538