Normally, we usually capture onkeydown or onkeyup events in input to do some commonly used processing, such as restricting the input of a certain type of characters, or restricting the length of input, and so on.
If you want to capture these onkeydown and onkeyup events in a Div, it is browser-compatible if you bind attributes directly to the nodes such as:
The code is as follows |
Copy Code |
<div onkeydown= "alert (" KeyDown ");" style= "width:200px; height:300px; " ></div> |
Then in IE can work, and in Firefox, Chrome is not working. There are, of course, two ways to solve this problem:
First, add contenteditable= "true" on the Div
The code is as follows |
Copy Code |
<meta charset= "UTF-8"/> <style type= "Text/css" > div { border:1px solid #000; width:500px; height:100px; } </style> <div contenteditable= "true" onkeydown= "Console.log (Event.keycode);" ></div> |
FireFox:
Chrome
This is a good way to use Div as an editor, so it is extremely handy, or just want to get keyboard input without entering characters can return false after onkeydown. Or you can use the second method.
The second is to add the TabIndex property on the Div
The code is as follows |
Copy Code |
<meta charset= "UTF-8"/> <style type= "Text/css" > div { border:1px solid #000; width:500px; height:100px; } </style> <div tabindex= "0" onkeydown= "Console.log (Event.keycode);" ></div> |
FireFox:
Chrome
TabIndex value is how much can be, as long as there is this attribute, tabindex the actual role of the user when the TAB key in order to switch the focus of the index settings, the results can solve this compatibility problem, and will not affect its own function use, when you give Div plus tabindex= After 0, you go to the Web page, press the TAB key. The first focus is still indexed to the tabindex=0 Div.
About a friend who asked me what is the use of capturing keyboard input events on a div? I think this problem is too esoteric, may be useless for some projects, but for some special Web applications is essential!