移动端禁止浏览器上下拉回弹,修复iOS最顶或最底时滚动卡顿

一、场景:在移动端各别浏览器中,滚动页面到最顶或最底部继续拉动touchend时会出现页面上下回弹,在iOS中还会在此时出现滚动卡顿。

二、主要代码(本文以Vue为框架进行表达)

1. 结构 

section为整个滚动区域,fixedBox为底部固定定位部分

2.样式

当section区域滚动时,在iOS中可能会出现滚动卡顿,此时给section部分添加样式:-webkit-overflow-scrolling: touch

    .box{
        height: 100vh;
        overflow: hidden;
    }
    .section{
        height: 100%;
        overflow-x: hidden;
        overflow-y: scroll;
        -webkit-overflow-scrolling: touch;
    }
    .fixedBox{
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        height: 0.48rem;
    }

3.解决临界(顶部或底部)页面回弹后卡顿问题

以上的设置可以使页面在iOS系统中滚动流畅,但当页面滚动到顶部或者底部时继续拉动会使整个页面被拉出可视区域,touchend时页面回弹,再滚动页面会出现卡顿情况,给出的很多处理方法event.preventDefault()阻止默认行为,这样同时会禁掉滚动事件,所以需要判断页面滚动的极值,如下:

    touchstart () {
        this.lastY = event.changedTouches[0].clientY // 点击屏幕时记录最后一次Y坐标
    }
    touchmove () {
        let y = event.changedTouches[0].clientY
        let st = this.$refs.sectionBox.scrollTop // 滚动条高度
        if (y >= this.lastY && st <= 0) { //若滚动到顶部且为下拉情况
            this.lastY = y
            event.preventDefault()
        }
        let clientHeight = document.querySelector('.section').clientHeight
        let scrollHeight = document.querySelector('.section').scrollHeight
        if ((st + clientHeight === scrollHeight) && y < this.lastY) { // 若滚动到底部且为上拉情况
            this.lastY = y
            event.preventDefault()
        }
        this.lastY = y
    }

 

你可能感兴趣的:(消灭bug)