如何使用Javascript更新占位符颜色? [英] How to update placeholder color using Javascript?
问题描述
我正在在线搜索,但没有找到任何东西. 我正在尝试使用javascript更新文本框的占位符颜色,但是我该怎么做呢? 我有一个颜色选择器,颜色正在变化.
I'm searching online and I didn't find anything. I'm trying to update the placeholder color of a textbox using javascript, but how can I do that? I have a color picker and the color is changing.
如果CSS中有类似的内容,该如何更新?
If I have something like this in my CSS, how can I update it?
::placeholder {
color: red;
}
<input placeholder="placeholder" />
是否有JavaScript命令可以对此进行编辑?
Is there a javascript command to edit this? Something like
document.getElementById('text').style.placeholderColor = newColor;
推荐答案
使用CSS变量.您还可以仅定位所需的元素
Use CSS variables. You can also target only the needed element
function update() {
document.querySelector('input[type=text]').style.setProperty("--c", "blue");
}
::placeholder {
color: var(--c, red);
}
<input type="text" placeholder="I will be blue">
<input type="number" placeholder="I will remain red">
<button onclick="update()">change</button>
CSS变量在修改您无法使用JS访问的伪元素(例如:before
/:after
/::placeholer/::selection
等)时非常有用.您只需定义自定义属性,即可在主属性上轻松更新元素和伪元素将继承它.
CSS variables are useful when it comes to modify pseudo elements that you cannot access with JS such as :before
/:after
/::placeholer/::selection
, etc. You simply define your custom property that you can easily update on the main element and the pseudo element will inherit it.
相关内容:使用jQuery选择和操作CSS伪元素,例如:: before和:: after
Related : Selecting and manipulating CSS pseudo-elements such as ::before and ::after using jQuery
这篇关于如何使用Javascript更新占位符颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!