通过 JavaScript 更改 CSS 伪元素样式

发布于 2024-10-08 18:30:26 字数 496 浏览 4 评论 0原文

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

例如,我想像这样动态设置滚动条的颜色:

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

并且我还希望能够像这样告诉滚动条隐藏:

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

但是,这两个脚本都返回:

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

是否有其他方法可以解决此问题?
跨浏览器互操作性并不重要,我只需要它能够在 webkit 浏览器中工作。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

你曾走过我的故事 2024-10-15 18:30:26

如果您对旧版浏览器中的一些优雅降级感到满意,则可以使用 CSS Vars。绝对是我在这里和其他地方见过的最简单的方法。

因此,在 CSS 中,您可以编写:

#editor {
  --scrollbar-background: #ccc;
}

#editor::-webkit-scrollbar-thumb:vertical {
  /* Fallback */
  background-color: #ccc;
  /* Dynamic value */
  background-color: var(--scrollbar-background);
}

然后在 JS 中,您可以在 #editor 元素上操作该值:

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

这里有许多使用 JS 操作 CSS 变量的其他示例: https://eager.io/blog/communicating- Between-javascript-and-css-with-css-variables/< /a>

If you're comfortable with some graceful degradation in older browsers you can use CSS Vars. Definitely the easiest of the methods I've seen here and elsewhere.

So in your CSS you can write:

#editor {
  --scrollbar-background: #ccc;
}

#editor::-webkit-scrollbar-thumb:vertical {
  /* Fallback */
  background-color: #ccc;
  /* Dynamic value */
  background-color: var(--scrollbar-background);
}

Then in your JS you can manipulate that value on the #editor element:

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

Lots of other examples of manipulating CSS vars with JS here: https://eager.io/blog/communicating-between-javascript-and-css-with-css-variables/

写给空气的情书 2024-10-15 18:30:26

要编辑您没有直接引用的现有样式表,需要迭代页面上的所有样式表,然后迭代每个样式表中的所有规则,然后迭代匹配选择器的字符串。

这是我发布的为伪元素添加新 CSS 的方法的参考,这是您从 js 设置的简单版本

Javascript set CSS :after styles

var addRule = (function (style) {
    var sheet = document.head.appendChild(style).sheet;
    return function (selector, css) {
        var propText = typeof css === "string" ? css : Object.keys(css).map(function (p) {
            return p + ":" + (p === "content" ? "'" + css[p] + "'" : css[p]);
        }).join(";");
        sheet.insertRule(selector + "{" + propText + "}", sheet.cssRules.length);
    };
})(document.createElement("style"));

addRule("p:before", {
    display: "block",
    width: "100px",
    height: "100px",
    background: "red",
    "border-radius": "50%",
    content: "''"
});

sheet.insertRule 返回新规则的索引,您可以使用它来获取对它的引用,这可以稍后用于编辑它。

To edit an existing one which you don't have a direct reference to requires iterating all style sheets on the page and then iterating all rules in each and then string matching the selector.

Here's a reference to a method I posted for adding new CSS for pseudo-elements, the easy version where you're setting from js

Javascript set CSS :after styles

var addRule = (function (style) {
    var sheet = document.head.appendChild(style).sheet;
    return function (selector, css) {
        var propText = typeof css === "string" ? css : Object.keys(css).map(function (p) {
            return p + ":" + (p === "content" ? "'" + css[p] + "'" : css[p]);
        }).join(";");
        sheet.insertRule(selector + "{" + propText + "}", sheet.cssRules.length);
    };
})(document.createElement("style"));

addRule("p:before", {
    display: "block",
    width: "100px",
    height: "100px",
    background: "red",
    "border-radius": "50%",
    content: "''"
});

sheet.insertRule returns the index of the new rule which you can use to get a reference to it for it which can be used later to edit it.

只涨不跌 2024-10-15 18:30:26

我通过使用 CSS 自定义属性执行以下操作来更改 ::selection 伪元素的背景:

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

//JavaScript Part
document.documentElement.style.setProperty("--selection-background", "#A4CDFF");

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");
眼泪淡了忧伤 2024-10-15 18:30:26

编辑:技术上有一种通过 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');

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');
时光清浅 2024-10-15 18:30:26

您无法将样式应用于 JavaScript 中的伪元素。

但是,您可以将

并在原始样式表中使用不同的伪元素样式定义它们。

You can't apply styles to psuedo-elements in JavaScript.

You can, however, append a <style> tag to the head of your document (or have a placeholding <style id='mystyles'> and change its content), which adjusts the styles. (This would work better than loading in another stylesheet, because embedded <style> tags have higher precedence than <link>'d ones, making sure you don't get cascading problems.

Alternatively, you could use different class names and have them defined with different psuedo-element styles in the original stylesheet.

赴月观长安 2024-10-15 18:30:26

我发布了一个与此问题类似但不完全相似的问题。

我找到了一种检索和更改伪元素样式的方法,并询问人们对该方法的看法。

我的问题是检索或更改伪元素的CSS规则

基本上,您可以通过以下语句获取样式:

document.styleSheets[0].cssRules[0].style.backgroundColor

并更改为:

document.styleSheets[0].cssRules[0].style.backgroundColor = newColor;

当然,您必须更改样式表和 cssRules 索引。阅读我的问题及其引起的评论。

我发现这适用于伪元素以及“常规”元素/样式。

I posted a question similar to, but not completely like, this question.

I found a way to retrieve and change styles for pseudo elements and asked what people thought of the method.

My question is at Retrieving or changing css rules for pseudo elements

Basically, you can get a style via a statement such as:

document.styleSheets[0].cssRules[0].style.backgroundColor

And change one with:

document.styleSheets[0].cssRules[0].style.backgroundColor = newColor;

You, of course, have to change the stylesheet and cssRules index. Read my question and the comments it drew.

I've found this works for pseudo elements as well as "regular" element/styles.

躲猫猫 2024-10-15 18:30:26

这是一个老问题,但我在尝试动态更改元素的 :before 选择器内容的颜色时遇到了一个问题。

我能想到的最简单的解决方案是使用 CSS 变量,当提出问题时,该解决方案不适用:

"#editor::-webkit-scrollbar-thumb:vertical {
    background: --editorScrollbarClr
}

更改 JavaScript 中的值:

document.body.style.setProperty(
    '--editorScrollbarClr', 
     localStorage.getItem("Color")
);

对于其他属性也可以执行相同的操作。

An old question, but one I came across when try to dynamically change the colour of the content of an element's :before selector.

The simplest solution I can think of is to use CSS variables, a solution not applicable when the question was asked:

"#editor::-webkit-scrollbar-thumb:vertical {
    background: --editorScrollbarClr
}

Change the value in JavaScript:

document.body.style.setProperty(
    '--editorScrollbarClr', 
     localStorage.getItem("Color")
);

The same can be done for other properties.

半岛未凉 2024-10-15 18:30:26

看起来 querySelector 不适用于伪类/伪元素,至少不适用于那些。我唯一能想到的就是动态添加样式表(或更改现有样式表)来完成您需要的操作。

这里有很多很好的例子:
如何在 Webkit (Safari/Chrome) 中动态加载 css 规则?< /a>

Looks like querySelector won't work with pseudo-classes/pseudo-elements, at least not those. The only thing I can think of is to dynamically add a stylesheet (or change an existing one) to do what you need.

Lots of good examples here:
How do I load css rules dynamically in Webkit (Safari/Chrome)?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文