通过JavaScript改变CSS伪元素样式 [英] Changing CSS pseudo-element styles via JavaScript
问题描述
是否可以通过JavaScript更改CSS伪元素样式?
例如,我想动态设置滚动条的颜色,如: p>
document.querySelector(#editor :: - webkit-scrollbar-thumb:vertical)。style.background = localStorage.getItem 颜色);
,我也希望能够让滚动条隐藏:
document.querySelector(#editor :: - webkit-scrollbar)style.visibility =hidden;
但是,这两个脚本都返回:
未捕获的TypeError:无法读取属性style为null
跨浏览器互操作性并不重要,我只需要在webkit浏览器中工作。
:技术上是通过JavaScript直接更改CSS伪元素样式的一种方式,这个答案描述了,但请永远不要这样做。这是解决这个问题的错误方法。
最接近在JavaScript中改变伪元素的样式是添加和删除类,然后使用伪元素与那些类。隐藏滚动条的示例:
CSS
.hidden-scrollbar :: - webkit-scrollbar {
visibility:hidden;
}
JavaScript
document.getElementById(editor)。classList.add('hidden-scrollbar');
要稍后删除同一个类,可以使用:
document.getElementById(editor)。classList.remove('hidden-scrollbar');
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.
EDIT: There is technically a way of directly changing CSS pseudo-element styles via JavaScript, as this answer describes, but please never, ever do that. It's the wrong way to solve this problem.
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');
这篇关于通过JavaScript改变CSS伪元素样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!