使用JavaScript检测何时光标不再在文本区域中

我想要做的是一个HTML文件,该文件检测textArea是否已写入某些内容。为了显示它,我更改了背景颜色,因此当textArea为空时使用灰色,而在上面写有文字的情况下使用白色。

为此,我开发了以下代码:

function prueba() {
    if (document.getElementById("text_1_3").value != "") {
        document.getElementById("text_1_3").style.background = "white";
    } else {
        document.getElementById("text_1_3").style.background = "rgb(174,170,170)";
    }
}
Text Area: <textarea id="text_1_3" style="background-color:rgb(174,170)" onclick="prueba();"></textarea>

此代码的主要问题是要更新背景色,我总是必须单击textArea。我想要的是,当我在textArea中输入任何内容并单击页面的任何部分时(即使没有引用,按钮...,请在“纯文本”中说),背景色已更新。

Ghadd 回答:使用JavaScript检测何时光标不再在文本区域中

只需使用CSS更改颜色,就不需要JavaScript。

textarea:focus {
  background-color: #FFF;
}
 
textarea { 
  background-color: rgb(174,170,170)
}
<textarea></textarea>

如果要使用JavaScript进行操作,则应使用焦点和模糊事件侦听器,而不是单击。

var ta = document.querySelector("textarea")
ta.addEventListener("focus",function () {
  ta.style.backgroundColor = "#FFF"
})

ta.addEventListener("blur",function () {
  ta.style.backgroundColor = "rgb(174,170)"
})
<textarea></textarea>

,

基于@epascarello的答案并进行一些更改,我得到了想要的! 这是代码:

<html>
Text Area: <textarea id="text_1_3" style="background-color:rgb(174,170)" onclick="prueba();"></textarea>
</html>
<script>
    var ta = document.querySelector("textarea")     
    ta.addEventListener("blur",function () {
        if (document.getElementById("text_1_3").value != "") {
            document.getElementById("text_1_3").style.background = "white";
        }
        else{
            document.getElementById("text_1_3").style.background = "rgb(174,170)";
        }
    })
</script>
本文链接:https://www.f2er.com/2636717.html

大家都在问