我想在用户放入一些文本时更改输入背景色,但是我的输入也有一个占位符,我不希望占位符更改颜色仅内容。
如何使用纯JavaScript实现这一目标?
<input type="text" placeholder="Enter your email adress">
if (formInput.length > 0) {
formInput[0].style.backgroundColor = "#f9f9f9";
}
您可以想象,即使在页面加载中的占位符中,它也会改变背景颜色。
检查输入值的长度。另外,在输入中没有任何内容时重置颜色。
(颜色更改为红色更明显)
let input = document.querySelector('input');
input.addEventListener('input', function() {
this.style.backgroundColor = (this.value.length > 0) ? 'lightcoral' : '';
});
<input type="text" placeholder="Enter your email adress">
只需检查输入的值:
let input = document.querySelector("input");
input.addEventListener("input", function() {
if (input.value.length > 0)
input.style.background = "#ff0000";
else
input.style.background = "none";
})
<input type="text" placeholder="Enter your email adress">
这是您想要的吗?
el =document.getElementById("email");
el.onkeyup = function(evt) {
el.style.background="red";
if(el.value.length==0)
el.style.background="none";
};
<input type="text" placeholder="Enter your email adress" id="email">