Manipulating Placeholder Color with JavaScript
Determining how to change a textbox's placeholder color through JavaScript can be perplexing. Although the ::placeholder selector can be used in CSS to define the placeholder color, there doesn't appear to be an immediate JavaScript equivalent.
Solution: CSS Variables
A viable solution is to leverage CSS variables. Here's how you can achieve this:
1. Define the CSS Variable:
:root { --placeholder-color: red; }
This creates a CSS variable named --placeholder-color with an initial value of red.
2. Apply the Variable to the Placeholder:
::placeholder { color: var(--placeholder-color); }
By referencing the --placeholder-color variable inside the ::placeholder rule, the placeholder color will now inherit the value defined in the root element.
3. Update the Variable Dynamically:
document.querySelector('input[type=text]').style.setProperty("--placeholder-color", "blue");
Using JavaScript, you can dynamically update the value of the --placeholder-color variable, which will subsequently change the color of the placeholder in all matching elements.
Example:
<input type="text" placeholder="placeholder"> <button onclick="update()">Change color</button>
function update() { document.querySelector('input[type=text]').style.setProperty("--placeholder-color", "blue"); }
Benefits:
The above is the detailed content of How to Change Placeholder Color Dynamically with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!