最近做的项目遇到了一个需求,在ios上微信网页下拉的时候不能出现黑底。如果要做的网页本来就设计成不能滚动的效果的话,普遍流传的方法是屏蔽掉 body 的 touchstart 或 touchmove 事件,但也会让所有滚动不可用,只适用部分页面。解决的方法很简单:
document.addEventListener('touchmove', function(e) {
e.preventDefault();
});
这样就可以禁止网页的滚动。但是当遇到网页内容超过窗口的100%的时候,禁止滚动就会导致用户没法滚动屏幕看到窗口以外的内容。因此这个办法不可行啦!
如果遇到了需要部分滚动的页面,在网上找到了以下办法:
$(function(){
if (!HTMLElement.currentStyle) {
function _getStyle(prop) {
var _s = window.getComputedStyle(this, null)
return prop ? _s[prop] : _s;
}
HTMLElement.prototype.currentStyle = _getStyle;
HTMLElement.prototype.getStyle = _getStyle;
}
// 阻止微信下拉出黑底插件
function PreventScroll() {
// // 非微信浏览器直接跳出 -- 后来发现好些浏览器都有这个坑,所以去掉
// var ua = navigator.userAgent.toLowerCase();
// if (!ua.match(/MicroMessenger/i)) return;
var elem = arguments || []; // 传入绑定的元素
var $elem = []; // 存储所有需要监听的元素
// 获取需要监听的元素
for (var i=0,len=elem.length; i<len; i++) {
var $e = document.querySelectorAll(elem[i]);
if (!$e) {console.error('您输入的元素不对,请检查'); return;}
for(var j=0; j<$e.length; j++) {
if ($e[j].currentStyle('overflow').match(/auto|scroll/i)) {
$elem.push($e[j]);
}
}
}
window.addEventListener('touchstart', function(e){
window.scroll_start = e.touches[0].clientY;
});
window.addEventListener('touchmove', prevent);
function prevent(e) {
var status = '11'; // 1容许 0禁止,十位表示向上滑动,个位表示向下滑动
var startY = window.scroll_start;
var currentY = e.touches[0].clientY;
var direction = currentY - startY > 0 ? '10' : '01'; // 当前的滚动方向,10 表示向上滑动
$elem.forEach(function(ele){
var scrollTop = ele.scrollTop,
offsetHeight = ele.offsetHeight,
scrollHeight = ele.scrollHeight;
if (scrollTop === 0) {
// 到顶,禁止向下滑动,或高度不够,禁止滑动
status = offsetHeight >= scrollHeight ? '00' : '01';
} else if (scrollTop + offsetHeight >= scrollHeight) {
// 到底,则禁止向上滑动
status = '10';
}
});
// output.innerHTML = status + ' ' + ++count;
// 如果有滑动障碍,如到顶到底等
if (status != '11') {
if (!(parseInt(status, 2) & parseInt(direction, 2))) {
e.preventDefault();
return;
}
}
}
}
PreventScroll('body');
});
调用PreventScroll();函数即可。但是此方法在安卓上可行,在ios上如果手一直拖动网页不放开,滚动条不消失的话,黑底还是会出现。。不知道大家有什么更完善的方法呢?