JS:在textarea中输入时更改div类,并在输入一段时间后更改

时间:2017-02-08 11:02:50

标签: javascript css keyboard-events

我的网页上有一个textarea和发送按钮。

如何在我打字的时候更改发送按钮的样式(到特定的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>
&#13;
&#13;
&#13;

但它不起作用。有什么问题?

1 个答案:

答案 0 :(得分:1)

解决方案:

Run CODE snippet以下&amp;输入textarea时键入。

看看这是否是您想要做的:

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>

您的CODE中的问题:

您的CODE不起作用的原因是:

  

您在活动onkeypress&amp;上更改了课程然后立即参加活动onkeyup

onkeypress表示当您按任意键&amp; onkeyup表示您释放相同的密钥。因此,当您输入onkeypress时,onkeyuponkeypressonkeyup ...继续发生并且课程一直在变化。

而我所做的是:

  
      
  1. 仅使用一个oninput事件 - 检测输入中的任何更改。

  2.   
  3. 内部事件处理程序使用setTimeout函数的计时器。这仅在3秒不活动或textarea为空时触发。

  4.