Stop keypress event

前端 未结 6 474
情歌与酒
情歌与酒 2020-12-29 19:19

How to stop keypress event in keydown.

I have a keydown handler in that I need to stop keypress event.

Ac

相关标签:
6条回答
  • 2020-12-29 19:49
    function onKeyDown(event) {   
      event.preventDefault();
    }
    

    http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-Event-preventDefault

    or

    function onsubmit(event) {
      return false;
    }
    

    return false to stop events propagation

    0 讨论(0)
  • 2020-12-29 19:55

    In opera, you have to use the keypress event to prevent the default actions for keyboard events. keydown works to prevent default action in all browsers but not in opera.

    See this long list of inconsistencies in keyboard handling across browsers.

    0 讨论(0)
  • 2020-12-29 20:04

    Here I stopped the event bubbling for up/dn/left/right keys:

        $(document).on("keydown", function(e) {
            if(e.keyCode >= 37 && e.keyCode <= 40) {
                e.stopImmediatePropagation();
                return;
            }
        });
    

    I also tried e.preventDefault or event.cancelBubble = true from the answers above, but they had no impact.

    0 讨论(0)
  • 2020-12-29 20:04

    Try event.cancelBubble = true in event handler.

    0 讨论(0)
  • 2020-12-29 20:04

    I was able to get the event.preventDefault(); to work in Safari and Firefox, but not IE7 or IE8.

    If you only want to disable the enter key, make sure that you're also checking for the key value (13 for Enter) and only setting event.preventDefault() for that key.

    Anyone able to come up with an answer for IE7/8 or Opera?

    0 讨论(0)
  • 2020-12-29 20:10

    Write,

        <script type="text/javascript">
          function keyDn(obj)
          {
            if(window["event"]["keyCode"]==48)  // key 0 will disabled keyPress event
             {
               obj["onkeypress"]=null;
              }
           }
          function keyPs(obj)
          {
            alert("Keypress");
          }
    
        </script>
    
      <form id="form1" runat="server">
        <div>
         <input type="text" onkeydown="keyDn(this)" onkeypress="keyPs(this)" />
        </div>
      </form>
    

    in keydown handler.

    0 讨论(0)
提交回复
热议问题