javascript - 如果输入背景颜色为空,则更改输入背景颜色
问题描述
我的问题是,当我在单击后留空时,我想将输入的背景设为红色。
这是我的 HTML:
<div id="name">
<label>Name<sup></sup></label> <br>
<input id="first" style="font-size:11pt;" type="text" name="name" placeholder="First Name" onChange='emptyField("first")'/>
<input id="last" style="font-size:11pt;" type="text" name="name" placeholder="Last Name" onChange='emptyField("last")'/>
</div>
这是我的javascript程序:
function emptyField(x) {
var field = document.getElementById(x);
if(field !== ""){
field.style.backgroundColor = "white";
}
else {
field.style.backgroundColor = "red";
}}
顺便提一下,我刚刚开始学习 HTML、CSS、JS 和 PHP。所以希望它对我来说不会太复杂理解。
解决方案
这是一个工作示例。注意focusout
事件的使用,而不是change
:
document.querySelectorAll('input[type="text"]').forEach(e => {
e.addEventListener('focusout', setInputBackground)
});
function setInputBackground() {
this.style.backgroundColor = !!this.value ? "white" : "red";
}
<div id="name">
<label>Name<sup></sup></label> <br>
<input id="firstname" style="font-size:11pt;" type="text" name="firstname" placeholder="First Name" />
<input id="lastname" style="font-size:11pt;" type="text" name="lastname" placeholder="Last Name" />
</div>
推荐阅读
- swift - 如何删除位置?
- xml - 如何使用 VB.net 将 .xml 银行对帐单转换为 .csv tex 文件?
- google-chrome - Chrome 中的 WebRTC 屏幕共享质量
- java - Runtime.getRuntime().availableProcessors() 在 Container-Optimized OS 上总是返回 1
- bash - 当用户与 ssh 断开连接时如何运行脚本
- java - 有什么方法可以在 Mockito 中使用 TestNG 进行超时验证
- simplex - 单纯形算法 - 最坏情况
- python-3.x - 如何使用 2 个列表并将值合并到一个字典中
- python-3.x - 如何从 OrangeML 模型中获取 Scikit-learn 模型输出?
- javascript - 如何使用猫鼬打开和关闭 TTL 索引?