如何使用 Javascript 更新占位符颜色?

How to update placeholder color using Javascript?

我正在网上搜索,但没有找到任何内容。 我正在尝试使用 javascript 更新文本框的占位符颜色,但我该怎么做? 我有一个颜色选择器,颜色正在改变。

如果我的 CSS 中有这样的内容,我该如何更新它?

::placeholder {
  color: red;
}
<input placeholder="placeholder" />

是否有 javascript 命令来编辑它? 像

document.getElementById('text').style.placeholderColor = newColor;

使用CSS 个变量。您也可以只定位需要的元素

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 等。您只需定义您可以在主元素上轻松更新的自定义 属性,伪元素将继承它。

相关:Selecting and manipulating CSS pseudo-elements such as ::before and ::after using jQuery

如其他答案所述,您不能像使用元素 .style:

那样 change pseudo-element styles inline. However, you can modify the CSS rule in the <style> itself, and you don't need a browser support ing CSS variables for that. Access the stylesheet and either get the existing rule or insert your own, then play with its style declarations

const {sheet} = Object.assign(document.head.appendChild(document.createElement("style")), {type: "text/css" });
const placeholderStyle = sheet.rules[sheet.insertRule("::placeholder {}")].style;
placeholderStyle.color = "red";

Object.assign(document.body.appendChild(document.createElement("input")), {
  type: "button", value: "Color!", onclick() {
    placeholderStyle.color = "#"+Math.round(Math.random()*0xFFF).toString(16).padStart("0",3);
}});
<input placeholder="placeholder" />

还有另一种方法,但有点hacky:使用JS将更多的CSS附加到body的末尾。假设规则相同,浏览器将用最新的 CSS 覆盖当前的 CSS。

function changeColor(toColor) {
  addCSS = document.createElement('style');
  addCSS.innerHTML = "::placeholder { color: " + toColor + "; }";
  document.body.append(addCSS);
}
::placeholder { color: green; }
<input type="text" placeholder="placeholder">
<button onclick="changeColor('red')">red</button>
<button onclick="changeColor('blue')">blue</button>

如果占位符颜色语义依赖于某些状态,可以间接设置

::placeholder { color: green; }
.warn::placeholder { color: red; }
<input id="test" placeholder="hello">
<button onclick="test.classList.toggle('warn')">Warning!</button>

在许多情况下,这根本不需要 javascript:

::placeholder { color: green; }
.color::after { content: 'green'; }

:checked + .color + ::placeholder { color: red; }
:checked + .color::after { content: 'red'; }
<input type="checkbox" id="color01">
<label class="color" for="color01">Color: </label>
<input placeholder="hello">