最近做移動端,總是遇到很蛋疼的問題, 決定把一些黑魔法記下來, 微信瀏覽器中想必會有很多事情讓我大前端小伙伴頭疼,
23333終於皇天不負有心人, 在網上找到了一個可以防頁面滾動滑到頂端或底部的時候, 漏出微信丑丑的灰色底[/偷笑]
原文網址:https://blog.ghostry.cn/program/702.html
我的核心代碼:
prevent:function () {
var startX = 0, startY = 0;
//touchstart事件
function touchSatrtFunc(evt) {
try
{
//evt.preventDefault(); //阻止觸摸時瀏覽器的縮放、滾動條滾動等
var touch = evt.touches[0]; //獲取第一個觸點
var x = Number(touch.pageX); //頁面觸點X坐標
var y = Number(touch.pageY); //頁面觸點Y坐標
//記錄觸點初始位置
startX = x;
startY = y;
} catch (e) {
alert('touchSatrtFunc:' + e.message);
}
}
document.addEventListener('touchstart', touchSatrtFunc, false);
var _ss = document.getElementById("contain");
_ss.ontouchmove = function (ev) {
var _point = ev.touches[0],
_top = _ss.scrollTop;
// 什么時候到底部
var _bottomFaVal = _ss.scrollHeight - _ss.offsetHeight;
// 到達頂端
if (_top === 0) {
// 阻止向下滑動
if (_point.clientY > startY) {
ev.preventDefault();
} else {
// 阻止冒泡
// 正常執行
ev.stopPropagation();
}
} else if (_top === _bottomFaVal) {
// 到達底部
// 阻止向上滑動
if (_point.clientY < startY) {
ev.preventDefault();
} else {
// 阻止冒泡
// 正常執行
ev.stopPropagation();
}
} else if (_top > 0 && _top < _bottomFaVal) {
ev.stopPropagation();
} else {
ev.preventDefault();
}
};
}