`return false` in an event handler attached by addEventListener or element.on*
Right let’s get this out the way first. Yes, I want to hide the context menu. No, I’m not trying to prevent someone lifting content off my page. Its intended use is input for an in-browser game and it开发者_StackOverflow will be limited to a specific area on the webpage.
Moving from the ideological to the technical...
var mouse_input = function (evt) {
// ...
return false;
}
document.onmousedown = mouse_input; // successful at preventing the menu.
document.addEventListener('mousedown', mouse_input, true); // unsuccessful
Could someone explain to me why the addEventListener
version is unable to stop the context menu from firing? The only difference I was able to see in Safari's Web Inspector was that document.onmousedown
had a isAttribute
value that was true whilst the addEventListener
version had the same value as false.
So my unfruitful search suddenly became fruitful.
var mouse_input = function (evt) {
evt.preventDefault();
}
document.addEventListener('contextmenu', mouse_input, false);
Works for Safari, Firefox, Opera. preventDefault()
stops the usual actions from happening. I had to change the event that was listened for to accommodate for Safari and it is more logical anyway. Further information: functions that implement EventListener shouldn’t return values so return false
had no effect.
To explain the difference .. element.onmousedown = somefunction;
is an absolute assignment; you are replacing the event handler on the element. element.addEventListener(...)
is, as the name implies, adding a handler in addition to any handler(s) already attached for the event.
精彩评论