web移动端常见问题解决方法

ios 微信返退键不能刷新页面

var UA = navigator.userAgent;
var isIOS = !!UA.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/i) || !!UA.match(/\(Maci[^;]+; .+Mac OS X/i);
var isWX = /micromessenger/i.test(UA);

if(isWX && isIOS){
  var isPageHide = false; 
  window.addEventListener('pageshow', function(){ 
    if (isPageHide) { 
      window.location.reload(); 
    } 
  }); 
  window.addEventListener('pagehide', function(){ 
    isPageHide = true; 
  }); 
}

禁止IOS双击自动滚动

/**
 * 修复IOS10+, viewport的user-scalable无效的问题
 * 添加下面样式:
 * html,body{height: 100%;overflow: hidden;}
 * body{overflow-y: scroll; -webkit-overflow-scrolling: touch; }
 */
(function(){
  var UA = navigator.userAgent.toLowerCase();

  if (UA.indexOf('iphone') >= 0 || UA.indexOf('ipad') >= 0) {
    // 禁止IOS滚动时,放大
    document.addEventListener('touchmove', function(event) {
      if (event.touches.length > 1) {
        event.preventDefault();
      }
    }, { passive: false });

    // 禁止IOS双击自动滚动
    var iLastTouch = null;
    document.addEventListener('touchend', function (event) {
      var a = new Date().getTime();
      iLastTouch = iLastTouch || a + 1;
      var c = a - iLastTouch;
      if (c < 500 && c > 0) {
        event.preventDefault();
        return false;
      }
      iLastTouch = a;
    }, { passive: false });

    // 手势
    document.addEventListener('gesturestart', function(event) {
      event.preventDefault();
    }, { passive: false });
  }
})();

阻止浏览器自带下拉滑动效果

// 阻止浏览器下拉滑动效果
var overscroll = function(el) {
  el.addEventListener('touchstart', function() {
    var top = el.scrollTop;
    var totalScroll = el.scrollHeight;
    var currentScroll = top + el.offsetHeight;

    if(top === 0) {
      el.scrollTop = 1;
    } else if(currentScroll === totalScroll) {
      el.scrollTop = top - 1;
    }
  });
  el.addEventListener('touchmove', function(evt) {
    console.log(evt.target);
    if(evt.target.tagName === 'CANVAS'){
      evt.preventDefault();
    }
    else if(el.offsetHeight < el.scrollHeight){
      evt._isScroller = true;
    }
  });
}
overscroll(document.querySelector('#app'));
document.body.addEventListener('touchmove', function (evt) {
  // 阻止默认的处理方式(阻止下拉滑动的效果)
  if(!evt._isScroller) {
    evt.preventDefault();
  }
}, {passive: false}); // passive 参数不能省略,用来兼容ios和android

参考:

https://segmentfault.com/a/1190000014134234

最后修改:2022 年 04 月 23 日 10 : 20 AM

发表评论