禁止 ios 橡皮筋效果

body 的橡皮筋效果触发,会导致内部元素无法滚动,解决方法很简单。

高版本 ios 只需对 body 这是 height:100%; overflow:hidden; 即可。

而低版本浏览器,则需要阻止body的默认行为 event.preventDefault()

但是执行时机是关键,否则整个窗口都将无法滚动,根据实际情况,上代码:

注意:  {passive: false} 一定要加,否则不生效。

const ios = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
if (ios) {
    let startY, endY, isScroll = false;
    document.body.addEventListener('touchstart', function(e) {
        startY = e.touches[0].pageY
    });
    document.body.addEventListener('touchmove', function(e) {
        if(isScroll) return
        e.preventDefault()
    }, {passive: false})

    document.querySelector('.scrollDom').addEventListener('touchmove', function(e) {
        endY = e.touches[0].pageY
        let domHeight = this.clientHeight,
        domScrollTop = this.scrollTop,
        scrollDomHeight = document.querySelector('.scrollChildren').clientHeight
          // 手指下滑,页面到达顶端不能继续下滑
        if ((endY > startY && domScrollTop <= 0) || (endY < startY && domHeight + domScrollTop >= scrollDomHeight)) {
            isScroll = false
        } else() {
            isScroll = true
        }
    }, {passive: false});
}

参考:https://www.cnblogs.com/cuncunjun/p/7493782.html

你可能感兴趣的:(移动端)