微信浏览器禁止页面下拉查看网址(不影响页面内部scroll)

此类事件是手机touchmove默认事件行为,可以通过js代码隐藏事件:

$(‘body’).on(‘touchmove’, function (event){ 
    event.preventDefault();
});
document.addEventListener('touchmove', {
    function(e){
        e.preventDefault()
    }
}, false);
document.body.addEventListener('touchmove', function (e) {
  e.preventDefault();
}, {passive: false});

当你在网上查找解决微信浏览器禁止页面出现下拉之类的关键字的时候,上面这些都是常见的结果。但是,这些东西其实用起来并不能解决问题,它们会把整个页面所有的滚动事件全部禁止掉,如果你页面内有某些元素本身就需要scroll的话,那就gg了,它们也被禁止了。

在网上翻了好久,终于找到一个较完美的解决方案了,代码如下:

var overscroll = function(el) {
  el.addEventListener('touchstart', function() {
    var top = el.scrollTop
      , totalScroll = el.scrollHeight
      , currentScroll = top + el.offsetHeight;
    if(top === 0) {
      el.scrollTop = 1;
    } else if(currentScroll === totalScroll) {
      el.scrollTop = top - 1;
    }
  });
  el.addEventListener('touchmove', function(evt) {
    if(el.offsetHeight < el.scrollHeight)
      evt._isScroller = true;
  });
}
overscroll(document.querySelector('.scroll'));
document.body.addEventListener('touchmove', function(evt) {
  if(!evt._isScroller) {
    evt.preventDefault();
  }
});

 上面这段代码是禁止掉页面scroll,同时允许部分元素上下滑动(需要在该元素上面添加一个class,类名叫scroll【当然也可以改成其他的,需要根据代码来改就行】),然后就完美解决问题啦!撒花✿✿ヽ(°▽°)ノ✿

 

 

参考文献:

1.https://github.com/luster-io/prevent-overscroll/blob/master/index.html

 

posted @ 2019-08-14 15:11  李某龙  阅读(6125)  评论(0编辑  收藏  举报