我正在开发一个基于 iPad 的网络应用程序,需要防止过度滚动,使其看起来不像网页。我目前正在使用它来冻结视口并禁用过度滚动:
document.body.addEventListener('touchmove',function(e){
e.preventDefault();
});
这对于禁用过度滚动非常有用,但我的应用程序有几个可滚动的 div,并且上面的代码阻止它们滚动.
我只针对 iOS 5 及更高版本,因此我避免了像 iScroll 这样的黑客解决方案。相反,我将这个 CSS 用于我的可滚动 div:
.scrollable {
-webkit-overflow-scrolling: touch;
overflow-y:auto;
}
这无需文档过度滚动脚本即可工作,但不能解决 div 滚动问题。
没有 jQuery 插件,有什么方法可以使用过度滚动修复但免除我的 $('.scrollable') div 吗?
EDIT:
我找到了一个不错的解决方案:
// Disable overscroll / viewport moving on everything but scrollable divs
$('body').on('touchmove', function (e) {
if (!$('.scrollable').has($(e.target)).length) e.preventDefault();
});
当您滚动经过 div 的开头或结尾时,视口仍然会移动。我也想找到一种方法来禁用它。
这解决了当您滚动超过 div 的开头或结尾时的问题
var selScrollable = '.scrollable';
// Uses document because document will be topmost level in bubbling
$(document).on('touchmove',function(e){
e.preventDefault();
});
// Uses body because jQuery on events are called off of the element they are
// added to, so bubbling would not work if we used document instead.
$('body').on('touchstart', selScrollable, function(e) {
if (e.currentTarget.scrollTop === 0) {
e.currentTarget.scrollTop = 1;
} else if (e.currentTarget.scrollHeight === e.currentTarget.scrollTop + e.currentTarget.offsetHeight) {
e.currentTarget.scrollTop -= 1;
}
});
// Stops preventDefault from being called on document if it sees a scrollable div
$('body').on('touchmove', selScrollable, function(e) {
e.stopPropagation();
});
请注意,如果您想在 div 没有溢出时阻止整个页面滚动,则此方法将不起作用。要阻止这种情况,请使用以下事件处理程序而不是上面的事件处理程序(改编自这个问题 https://stackoverflow.com/a/16446081/40352):
$('body').on('touchmove', selScrollable, function(e) {
// Only block default if internal div contents are large enough to scroll
// Warning: scrollHeight support is not universal. (https://stackoverflow.com/a/15033226/40352)
if($(this)[0].scrollHeight > $(this).innerHeight()) {
e.stopPropagation();
}
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)