通过 JavaScript 更改 CSS 伪元素样式 [英] Changing CSS pseudo-element styles via JavaScript

查看:45
本文介绍了通过 JavaScript 更改 CSS 伪元素样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过 JavaScript 更改 CSS 伪元素样式?

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:

未捕获的类型错误:无法读取 null 的属性样式"

Uncaught TypeError: Cannot read property 'style' of null

还有其他方法可以解决这个问题吗?
跨浏览器互操作性并不重要,我只需要它在 webkit 浏览器中工作即可.

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

推荐答案

编辑:技术上有一种通过 JavaScript 直接更改 CSS 伪元素样式的方法,例如 这个答案描述,但这里提供的方法更可取.

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.

最接近在 JavaScript 中改变伪元素样式的方法是添加和删除类,然后将伪元素与这些类一起使用.隐藏滚动条的示例:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆