简体   繁体   中英

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.

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.

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.

Does anybody knows how to get it works again, or is it a correct behavior for the latest Chrome ? Would appreciate any help, thanks.

There was a change in 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).

To get it work again, passive property can be set to 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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