我有一个无法滚动的 IOS Web 应用程序。出于这个原因,我想停用滚动。为此,我使用元素的 ontouchmove 属性并让它调用一个使用 element.preventDefault 的函数。 但是,当它在文本区域或输入元素上启动时,我无法检测到任何触摸事件,即使该元素已禁用!我还尝试通过 JavaScript 的 addEventlistener 将 touchmove 或 touchstart 事件绑定(bind)到这些元素,但没有成功!
这是我的 JavaScript:
function onBodyLoad() {
document.addEventListener( "touchstart", doNotScroll, true );
document.addEventListener( "touchmove", doNotScroll, true );
}
function doNotScroll( event ) {
event.preventDefault();
event.stopPropagation();
}
感谢您的帮助!
最佳答案
我认为我已经使用“pointer-events”CSS 属性找到了解决此问题的绝佳方法:
function setTextareaPointerEvents(value) {
var nodes = document.getElementsByTagName('textarea');
for(var i = 0; i < nodes.length; i++) {
nodes[i].style.pointerEvents = value;
}
}
document.addEventListener('DOMContentLoaded', function() {
setTextareaPointerEvents('none');
});
document.addEventListener('touchstart', function() {
setTextareaPointerEvents('auto');
});
document.addEventListener('touchmove', function(e) {
e.preventDefault();
setTextareaPointerEvents('none');
});
document.addEventListener('touchend', function() {
setTimeout(function() {
setTextareaPointerEvents('none');
}, 0);
});
这将使 iOS 上的 Mobile Safari(其他尚未测试的)忽略滚动的文本区域,但允许像往常一样设置焦点等。
关于iOS/WebKit : touchmove/touchstart not working on input & textarea,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4178725/