admin管理员组文章数量:1401149
Consider the following scenario:
document.body.style.setProperty("--text", "world")
body::before{
--text: "Hello";
content: var(--text, "...");
}
body::after{
content: var(--text, "...");
}
Consider the following scenario:
document.body.style.setProperty("--text", "world")
body::before{
--text: "Hello";
content: var(--text, "...");
}
body::after{
content: var(--text, "...");
}
CSS is able to set a type to the variable by having the value of the custom property --text
with quotes, but when done the same with javascript setProperty
this is the oute of the (inspected) node (in Chrome) which is without quotes, which makes it impossible to use as content
value of a pseudo-element:
Can this somehow be done via JS using setProperty
? (assuming the element already has a bunch of stuff in its style
attribute which I don't want to mess with.
-
Does it have to be a CSS variable? Can't you just set a data-property on
body
and then usecontent: attr(data-property)
on your pseudo-elements? – Rickard Elimää Commented Oct 13, 2020 at 16:05 - 1 Yes, it has to be Rickard – vsync Commented Oct 13, 2020 at 18:01
2 Answers
Reset to default 5Set it as so:
document.body.style.setProperty("--text", "'world'")
The problem is now this:
var word = "world";
document.body.style.setProperty("--text", word)
body::before{
--text: "Hello";
content: var(--text, "...");
}
body::after{
content: var(--text, "...");
}
Which can be solved by:
document.body.style.setProperty("--text", JSON.stringify(word))
If one is utilizing data-binding properties, e.g. Knockout JS, you could set the "" string value using Template literal syntax
HTML
<div data-bind="style: {'--text': self.Word() }" style='--prefix: "";'>
JS
self.Word = ko.observable(`"${word}"`)
本文标签: Set CSS custom propertyvariable from javascript as type StringStack Overflow
版权声明:本文标题:Set CSS custom propertyvariable from javascript as type String - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744277221a2598472.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论