Home >Web Front-end >JS Tutorial >Introduction to the difference between onkeyup and onkeydown in javascript_Basic knowledge

Introduction to the difference between onkeyup and onkeydown in javascript_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 17:34:571493browse

I encountered a problem yesterday when I was writing the last dynamically generated year, month, day drop-down box and text box to limit input. When typing in the text box, I had to start calculating how many words were entered in the text box. Naturally, I thought of the onkeydown event. , and then calculate the method of value.length, look at the code

Copy the code The code is as follows:

moto.onkeydown=function(){
var curlen= this.value.length;
shuru.innerHTML=curlen;
shuru2.innerHTML= (200-curlen);
if(curlen>= 200){
this.value=this.value.substring(0,200);
curlen=200;
shuru.innerHTML=200;
shuru2.innerHTML=0;
return false;
}
}

It turned out that the word count was wrong after inputting the text. After inputting 4 characters, I found that the word count still showed 0
Introduction to the difference between onkeyup and onkeydown in javascript_Basic knowledge
I thought about it for a long time, and finally changed onkeydown to onkeyup, and everything was fine
Introduction to the difference between onkeyup and onkeydown in javascript_Basic knowledge
I checked and found that the two events are different
onkeydown is triggered when pressed Yes, the key value is not output at this time. onkeyup is executed when the button is lifted. At this time, the key value is already available. It doesn’t matter how long you press it. For example, if you add these two events to the input box,
Copy the code The code is as follows:




You will understand when you look at these two different running results!
Copy code The code is as follows:





Insert title here

< ;body>





onkeydown is triggered when the key is pressed. The value is not output.
Onkeyup is executed when the button is lifted. At this time, the key value is already available.
It doesn’t matter how long you press it. For example, if you add these two events to the input box,
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn