如果提交了某个值,如何更改输入类型="text" 中占位符文本的颜色?
How do i change the color of the placeholder text in an input type="text" if a certain value is submitted?
我有一个栏,用户可以在其中输入地址。如果给定的地址无效,则删除输入的 texed 并将占位符文本更改为“找不到地址”。我也希望占位符文本变成红色,但我不太明白如何。
这是索引中的代码
<input type="text" id="searchAdress" placeholder="Type an adress, city or country" />
这是js中的代码
if (data.length > 0){
document.getElementById("searchAdress").value='';
document.getElementById("searchAdress").placeholder = "Type an adress, city or country";
} else {
document.getElementById("searchAdress").value='';
document.getElementById("searchAdress").placeholder = "Adress not found";
}
通常在 CSS 中,您会使用 ::placeholder
选择器来修改占位符颜色。在 JavaScript 中,您无法真正修改 CSS 伪选择器,因此您必须为每个占位符颜色分配特定的 class,如下所示:
var input = document.getElementById("searchAdress");
function validate(){
var value = input.value;
if(value.length>0){
//Valid
input.value="";
input.placeholder="Got it";
clearOtherClasses(input);
input.classList.add("green");
}else{
//Invalid
input.value="";
input.placeholder="Nope";
clearOtherClasses(input);
input.classList.add("red");
}
}
function clearOtherClasses(element){
element.className="";
}
.green::placeholder{
color:green;
}
.red::placeholder{
color:red;
}
<input type="text" id="searchAdress" placeholder="Type an adress, city or country"><button onclick="validate()">validate</button>
<hr>
Enter nothing to toggle red placeholder text. Enter something to toggle green.
函数 clearOtherClasses()
用于防止颜色冲突 classes(例如,输入同时具有 green
class 和 red
class).
我有一个栏,用户可以在其中输入地址。如果给定的地址无效,则删除输入的 texed 并将占位符文本更改为“找不到地址”。我也希望占位符文本变成红色,但我不太明白如何。
这是索引中的代码
<input type="text" id="searchAdress" placeholder="Type an adress, city or country" />
这是js中的代码
if (data.length > 0){
document.getElementById("searchAdress").value='';
document.getElementById("searchAdress").placeholder = "Type an adress, city or country";
} else {
document.getElementById("searchAdress").value='';
document.getElementById("searchAdress").placeholder = "Adress not found";
}
通常在 CSS 中,您会使用 ::placeholder
选择器来修改占位符颜色。在 JavaScript 中,您无法真正修改 CSS 伪选择器,因此您必须为每个占位符颜色分配特定的 class,如下所示:
var input = document.getElementById("searchAdress");
function validate(){
var value = input.value;
if(value.length>0){
//Valid
input.value="";
input.placeholder="Got it";
clearOtherClasses(input);
input.classList.add("green");
}else{
//Invalid
input.value="";
input.placeholder="Nope";
clearOtherClasses(input);
input.classList.add("red");
}
}
function clearOtherClasses(element){
element.className="";
}
.green::placeholder{
color:green;
}
.red::placeholder{
color:red;
}
<input type="text" id="searchAdress" placeholder="Type an adress, city or country"><button onclick="validate()">validate</button>
<hr>
Enter nothing to toggle red placeholder text. Enter something to toggle green.
函数 clearOtherClasses()
用于防止颜色冲突 classes(例如,输入同时具有 green
class 和 red
class).