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
Linda HamiltonOriginal
2024-12-24 07:09:15633browse

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;
}

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);
}

JavaScript Manipulation

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

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

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:
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