Set CSS custom propertyvariable from javascript as type String - Stack Overflow

Consider the following scenario:document.body.style.setProperty("--text", "world")

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.

Share Improve this question asked Oct 13, 2020 at 15:29 vsyncvsync 131k59 gold badges340 silver badges423 bronze badges 2
  • Does it have to be a CSS variable? Can't you just set a data-property on body and then use content: 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
Add a ment  | 

2 Answers 2

Reset to default 5

Set 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}"`)

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744277222a4566390.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信