我的网页上有一个文本区域和发送按钮。
如何在键入时更改发送按钮的样式(到特定的 CSS 类(,然后在一段时间不键入到另一个 CSS 类后更改
。此外,删除消息时,发送按钮的样式必须更改回原始 CSS 类。
这是我尝试过的代码:
function isTyping(val) {
if (val == 'true') {
document.getElementsByClassName('send')[0].innerHTML = "Class1";
} else {
document.getElementsByClassName('send')[0].innerHTML = "Class2";
}
}
.type-message:focus + .send {
background-color: red;
}
.class1 {
display: block;
width: 50px;
height: 20px;
background-color: red;
}
.class2 {
display: block;
width: 50px;
height: 20px;
background-color: yellow;
}
<textarea class="type-message" onkeypress="isTyping('true'); timer=5;" onkeyup="isTyping('false')" name="textarea" cols="45" rows="5">
</textarea>
<div class="send">Class2</div>
但它不起作用。怎么了?
解决方案:
Run CODE snippet
下面并键入文本区域。
看看这是否是你想要做的:
var delay = 3000; // that's 3 seconds of not typing
var timer = null;
function isTyping() {
clearTimeout(timer);
var value = document.getElementById('text').value;
if( value ) {
document.getElementById('send').innerHTML = "Typing";
document.getElementById("send").className = "typing";
timer = setTimeout(notTyping, delay);
}
else {
notTyping();
}
}
function notTyping() {
document.getElementById('send').innerHTML = "Not Typing";
document.getElementById("send").className = "not-typing";
}
#send {
display: block;
width: 200px;
height: 20px;
}
.not-typing {
background-color: yellow;
}
.typing {
background-color: red;
}
<textarea class="type-message" oninput="isTyping()" id="text" name="textarea" cols="45" rows="5"></textarea>
<div id="send" class="not-typing">Not Typing</div>
代码中的问题:
您的代码不起作用的原因是:
您在事件
onkeypress
上更改了类,然后立即更改了事件onkeyup
的类。
onkeypress
表示当您按下任何键时onkeyup
表示当您松开相同的键时。所以当你输入onkeypress
、onkeyup
、onkeypress
、onkeyup
... 不断发生,阶级不断变化。
相反,我所做的是:
仅使用一个
oninput
事件 - 检测输入中的任何更改。内部事件处理程序使用
setTimeout
函数的计时器。这仅在不活动 3 秒或textarea
为空时触发。