Home >Web Front-end >CSS Tutorial >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!