Home > Web Front-end > CSS Tutorial > How Can I Dynamically Change CSS Pseudo-Element Styles Using JavaScript?

How Can I Dynamically Change CSS Pseudo-Element Styles Using JavaScript?

Linda Hamilton
Release: 2024-12-24 07:09:15
Original
701 people have browsed it

How Can I Dynamically Change CSS Pseudo-Element Styles Using JavaScript?

Manipulating CSS Pseudo-Element Styles Dynamically Through JavaScript

While attempting to dynamically alter CSS pseudo-element styles via JavaScript, users may encounter the "Uncaught TypeError: Cannot read property 'style' of null" error. This article explores an alternative approach leveraging CSS variables to achieve cross-browser compatibility in WebKit browsers specifically.

CSS Variable-Based Approach

In CSS, define a CSS variable for the scrollbar background color:

#editor {
  --scrollbar-background: #ccc;
}
Copy after login

Then, apply the variable to the scrollbar pseudo-element:

#editor::-webkit-scrollbar-thumb:vertical {
  /* Fallback color */
  background-color: #ccc;
  /* Dynamic value */
  background-color: var(--scrollbar-background);
}
Copy after login

JavaScript Manipulation

In JavaScript, set the CSS variable on the #editor element:

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

This method allows for dynamic manipulation of the scrollbar background color, even in older browsers that do not support modern CSS features.

The above is the detailed content of How Can I Dynamically Change CSS Pseudo-Element Styles Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

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