This article introduces how to solve the incompatibility problem between onkeydown and onkeyup on Firefox and Google. I hope this tutorial will help you.
Under normal circumstances, we usually capture the onkeydown or onkeyup event in the input to do some common processing, such as limiting the input of a certain type of characters, or limiting the input length.
If you want to capture these onkeydown and onkeyup events in the DIV, It is browser-compatible. If you directly bind attributes to the node, for example:
The Code is as follows: |
Copy code |
<Div onkeydown = "alert (" keydown ");" style = "width: 200px; height: 300px;"> </div> |
It works in IE, but in FireFox and Chrome. Of course, there are two solutions:
First, add contenteditable = "true" to 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 method is suitable for using DIV as an editor. It is extremely convenient, or you can return false after onkeydown if you only want to obtain the keyboard input without entering characters. Or you can use the second method.
Second, add the tabindex attribute to 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
The value of tabindex can be any number. As long as this attribute exists, the actual function of tabindex is to set the index for switching focus sequence when you press the tab key. The result can solve this compatibility problem, it does not affect its function usage. When you add tabindex = 0 to the DIV, you enter the webpage and press the tab key. The first focus is still directed to the DIV with tabindex = 0.
A friend asked me what is the use of capturing keyboard input events on the DIV? I think this problem is too unpredictable. It may be useless for some projects, but it is essential for some special web applications!