我在想如何在不使用内联样式的情况下使用 css 变量。我以为我可以使用这个:
[data-color] {
--color: attr(data-color color, green);
}
* {
color: var(--color, blue);
}
<div data-color="red">hello</div>
似乎 attr 仅适用于伪选择器(并且可能仅适用于
content:
属性),但 MDN attr page说:The attr() CSS function is used to retrieve the value of an attribute of the selected element and use it in the stylesheet. It can also be used on pseudo-elements, in which case the value of the attribute on the pseudo-element's originating element is returned.
甚至有演示,但它在 Linux 上的 Chrome 中不起作用,所以对我来说没有用。它甚至不适用于 Linux 上的 Firefox。
有没有其他方法可以在没有内联样式和不写动态的情况下使用 css 变量
<style></style>
和随机数?
最佳答案
还没有。在同一个链接中,您可以阅读:
Note: The attr() function can be used with any CSS property, but support for properties other than content is experimental, and support for the type-or-unit parameter is sparse.
仍然没有浏览器支持
attr()
对于不同于内容的属性,也不支持类型或单位。值得注意的是,您可以使用
attr()
在 CSS 变量中,但稍后需要与内容一起使用。 CSS 变量只是一个中间值,所以我们不评估基于变量的支持,而是基于将使用该变量的属性。[data-color] {
--color: attr(data-color);
}
*::before {
content: var(--color, "default");
color:blue;
}
<div data-color="red">hello</div>
关于css - 使用 attr 设置与 CSP 一起使用的内联 css 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64587414/