Modifying CSS Pseudo-Element Styles with JavaScript: A Closer Look
Is it possible to dynamically alter the style of CSS pseudo-elements through JavaScript? Suppose we wish to set the scrollbar's color and hide it altogether. Using scripts like the following, however, returns a "Cannot read property 'style' of null" error:
document.querySelector("#editor::-webkit-scrollbar-thumb:vertical").style.background = localStorage.getItem("Color"); document.querySelector("#editor::-webkit-scrollbar").style.visibility = "hidden";
Let's explore an alternative approach that works effectively in Webkit browsers and allows for graceful degradation in others.
Utilizing CSS Vars for Styling
Modern browsers offer CSS Variables (CSS Vars), which provide a powerful way to define and manipulate custom CSS properties from JavaScript. By employing CSS Vars, you can achieve the desired styling effects while maintaining cross-browser compatibility.
In your CSS, define the CSS Var --scrollbar-background and apply it to the scrollbar's thumb:
#editor { --scrollbar-background: #ccc; } #editor::-webkit-scrollbar-thumb:vertical { background-color: #ccc; background-color: var(--scrollbar-background); }
Now, in your JavaScript, modify the --scrollbar-background property on the #editor element:
document.getElementById("#editor").style.setProperty('--scrollbar-background', localStorage.getItem("Color"));
By utilizing CSS Vars in conjunction with JavaScript, you can effortlessly change pseudo-element styles and ensure compatibility across a wide range of web browsers.
The above is the detailed content of Can JavaScript Dynamically Modify CSS Pseudo-Element Styles?. For more information, please follow other related articles on the PHP Chinese website!