简体   繁体   中英

Javascript: invoke default keydown event handler

I'd like to invoke default keydown event handler from javascript. Is it possible?

If the event has an explicit event handler you can just invoke it directly:

// Precondition - the element has an explicit handler registered
element.onkeydown();

Otherwise, there's no way to explicitly tell the browser to do "what it would have done anyway". The only way to get this to happen is to not stop the event from bubbling - which can be a real pain if you want to set a timeout and then allow the event to continue, it's essentially not possible.

In most cases, though, you can invoke your own code on an event handler and let the keyDown event continue to the browser. And if this isn't possibel for whatever reason, you can usually write your own method that will simulate the effects of the event (eg change the content of an input field, submit the form, etc.)

There is no default keydown event. The keydown event occurs when the key is pressed on any form elements, followed immediately by the keypress event, and possibly the textInput event on text box when you enter a value. Then the keyup event is generated when the key is released The following example shows the use of the onKeyDown event handler to display a message in the text box.

<body><form action="" method="POST" id="myForm"><input type="text" name="myText" onKeyDown="changeVal()"><script type="text/javascript" language="JavaScript">s1 = new String(myForm.myText.value)function changeVal() {    s1 = "You pressed a key"
myForm.myText.value = s1.toUpperCase() }</script></form></body>

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