Changing CSS pseudo-element styles via JavaScript

2020-05-10 06:31发布

Is it possible to change a CSS pseudo-element style via JavaScript?

For example, I want to dynamically set the color of the scrollbar like so:

document.querySelector("#editor::-webkit-scrollbar-thumb:vertical").style.background = localStorage.getItem("Color");

and I also want to be able to tell the scrollbar to hide like so:

document.querySelector("#editor::-webkit-scrollbar").style.visibility = "hidden";

Both of these scripts, however, return:

Uncaught TypeError: Cannot read property 'style' of null

Is there some other way of going about this?
Cross-browser interoperability is not important, I just need it to work in webkit browsers.

8条回答
劫难
2楼-- · 2020-05-10 07:31

EDIT: There is technically a way of directly changing CSS pseudo-element styles via JavaScript, as this answer describes, but the method provided here is preferable.

The closest to changing the style of a pseudo-element in JavaScript is adding and removing classes, then using the pseudo-element with those classes. An example to hide the scrollbar:

CSS

.hidden-scrollbar::-webkit-scrollbar {
   visibility: hidden;
}

JavaScript

document.getElementById("editor").classList.add('hidden-scrollbar');

To later remove the same class, you could use:

document.getElementById("editor").classList.remove('hidden-scrollbar');
查看更多
仙女界的扛把子
3楼-- · 2020-05-10 07:33

I changed the background of the ::selection pseudo-element by using CSS custom properties doing the following:

/*CSS Part*/
:root {
    --selection-background: #000000;
}
#editor::selection {
    background: var(--selection-background);
}

//JavaScript Part
document.documentElement.style.setProperty("--selection-background", "#A4CDFF");
查看更多
登录 后发表回答