使用下面的html和Javascript我计算在输入字段中输入的字符数,并将它们限制为30.我还向用户显示一个计数器。
此计数器会更改此事件的值:onfocus
,onKeyDown
,onKeyUp
,onpaste
。
我无法让onpaste
工作。当用户使用“CTRL V”粘贴时,计数器会更改值,但使用鼠标/右键单击粘贴时,计数器不会更改。我做错了什么?
Jsfiddle: https://jsfiddle.net/ow3ubgp0/
HTML:
<input readonly type="text" name="countdown1" size="5" value="30" />
<input type="text" id="my_text_input" name="my_text_input" onfocus="limitText(this.form.my_text_input,this.form.countdown1,30);" onKeyDown="limitText(this.form.my_text_input,this.form.countdown1,30);" onKeyUp="limitText(this.form.my_text_input,this.form.countdown1,30);" onpaste="limitText(this.form.my_text_input,this.form.countdown1,30);" />
使用Javascript:
function limitText(limitField, limitCount, limitNum) {
if (limitField.value.length > limitNum) {
limitField.value = limitField.value.substring(0, limitNum);
} else {
limitCount.value = limitNum - limitField.value.length;
}
}
答案 0 :(得分:1)
你好用下面的代码检查
我希望它有所帮助
<html>
<form>
<input readonly type="text" name="countdown1" size="5" value="30" />
<input type="text" id="my_text_input" name="my_text_input" onfocus="limitText(this.form.my_text_input,this.form.countdown1,30);" onKeyDown="limitText(this.form.my_text_input,this.form.countdown1,30);" onKeyUp="limitText(this.form.my_text_input,this.form.countdown1,30);" onpaste="limitText(this.form.my_text_input,this.form.countdown1,30);" onChange="limitText(this.form.my_text_input,this.form.countdown1,30);" oninput="limitText(this.form.my_text_input,this.form.countdown1,30);"/>
</form>
<script>
function limitText(limitField, limitCount, limitNum) {
if (limitField.value.length > limitNum) {
limitField.value = limitField.value.substring(0, limitNum);
} else {
limitCount.value = limitNum - limitField.value.length;
}
}
</script>
</html>
答案 1 :(得分:0)
这是一个有效的fiddle。
oninput
:当用户在某个字段中写入内容时执行JavaScript。
<form>
<input readonly type="text" name="countdown1" size="5" value="30" />
<input onfocus="limitText(this.form.my_text_input,this.form.countdown1,30);" onKeyDown="limitText(this.form.my_text_input,this.form.countdown1,30);" onKeyUp="limitText(this.form.my_text_input,this.form.countdown1,30);" onpaste="limitText(this.form.my_text_input,this.form.countdown1,30);"
oninput="limitText(this.form.my_text_input,this.form.countdown1,30);" type="text" id="my_text_input" name="my_text_input" /></input>
</form>
答案 2 :(得分:0)
limitField.value.length为零。它是粘贴的先前值的值。
所以它永远不到limitNum。