Home > Web Front-end > CSS Tutorial > Can JavaScript Dynamically Modify CSS Pseudo-Element Styles?

Can JavaScript Dynamically Modify CSS Pseudo-Element Styles?

Linda Hamilton
Release: 2024-12-18 02:02:14
Original
825 people have browsed it

Can JavaScript Dynamically Modify CSS Pseudo-Element Styles?

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";
Copy after login

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);
}
Copy after login

Now, in your JavaScript, modify the --scrollbar-background property on the #editor element:

document.getElementById("#editor").style.setProperty('--scrollbar-background', localStorage.getItem("Color"));
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template