event.preventDefault() works on Chrome, Firefox, b

2019-09-02 18:10发布

问题:

This HTML / JS code :

<script>
window.onload = function(e) {
window.onkeydown = function(event) {
        if (event.ctrlKey && (event.keyCode == 61 || event.keyCode == 187)) 
        {
          event.preventDefault();
          alert("hello");
          return false;
        }
      }
}
</script>
<p>Blah</p>

overrides the browser CTRL+PLUS 's ZOOM keyboard shortcut.

It works on Firefox, Chrome, but not with Safari : with Safari, if you do CTRL+PLUS on this page, the alert("hello") is launched, but the browser's zooming is also changed !

This means that event.preventDefault(); hasn't worked like it should have worked.

How to use event.preventDefault() with Safari ?

Note: I already tried as well with StopPropagation, but it doesn't solve the problem.

回答1:

Seems like this is problem with ctrlKey. Assuming you use Mac OS X system you need to check for metaKey too, so your code should be:

if ((event.ctrlKey || event.metaKey) && (event.keyCode == 61 || event.keyCode == 187))


回答2:

We probably have different keyboard layouts or something, but my + and - signs on my numpad have the key code values 107 and 109. (http://www.asquare.net/javascript/tests/KeyCode.html)

The code snippet below works in safari for me.

window.onkeydown = function (event) {
    if (event.ctrlKey && (event.keyCode == 107 || event.keyCode == 109)) {
        event.preventDefault();
        alert("hello");
    }
}



回答3:

You can try this:

window.onkeydown = function(event) {
        if (event.ctrlKey && (event.keyCode == 61 || event.keyCode == 187)) 
        {
          if (event.preventDefault){
             event.preventDefault();
          }
          else {
             event.returnValue = false;
          }
          alert("hello");
          return false;
        }
      }
}


回答4:

The key codes for zoom are different across browsers:

Opera   MSIE  Firefox  Safari  Chrome 
 61     187     107     187     187      = +             
109     189     109     189     189      - _ 

Also try :

event.stopImmediatePropagation();

To prevent other handlers from executing.