简体   繁体   English

event.preventDefault不适用于Chrome中的“ document” /“ document.body”元素

[英]event.preventDefault is not working for “document” / “document.body” elements in Chrome

I have some functionality that preventing touch events on devices (in some specific cases). 我有一些功能可以防止设备上发生触摸事件(在某些特定情况下)。 It worked well till the last update of the Chrome. 在Chrome的最新更新之前,它运行良好。

After the update, trying to prevent the events that I get from document or document.body is not working anymore, but it works if I listen to events from a some specific element. 更新后,尝试防止从documentdocument.body获得的事件不再起作用,但是如果我侦听某个特定元素中的事件,该方法将起作用。

For example: 例如:

//this not works
document.addEventListener("touchmove", function(event) {
    event.preventDefault();
});

//this one works
document.querySelector(".container").addEventListener("touchmove", function(event) {
    event.preventDefault();
});

This is not very convenient behavior, since I have a lot of children inside the body element and can't change this structure. 这不是很方便的行为,因为我在body元素内有很多孩子,并且无法更改此结构。

Does anybody knows how to get it works again, or is it a correct behavior for the latest Chrome ? 有谁知道如何使其重新运行,或者它对于最新的Chrome是正确的行为吗? Would appreciate any help, thanks. 感谢您的帮助,谢谢。

There was a change in Chrome 56 : Chrome 56发生变化

With this change touchstart and touchmove listeners added to the document will default to passive:true (so that calls to preventDefault will be ignored). 进行此更改后,添加到文档中的touchstart和touchmove侦听器将默认为Passive:true(这样,对preventDefault的调用将被忽略)。

To get it work again, passive property can be set to false . 为了使它再次起作用,可以将passive属性设置为false

document.addEventListener("touchmove", function(event) {
    event.preventDefault();
}, {passive: false});

Not sure if it reasonable to force event handler to be not a passive, but anyway this can be taken into account. 不确定强制事件处理程序不是被动的是否合理,但是无论如何都可以考虑到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM