通过JS更新变量值后,CSS伪类消失

时间:2019-05-10 05:34:53

标签: javascript css frontend pseudo-element css-variables

我希望能够通过JS更新CSS变量,但是当我对变量进行更新时,CSS伪元素被破坏了(即消失了)。

这是SCSS代码:

:root {
  --test-thing: "";
}

.folder-1-open span::after {
    width: 90%;
    height: 85%;
    bottom: 0;
    left: 5%;
    background-color: #fff;
    z-index: 3;
    content: var(--test-thing);
}

我正在尝试这样操作变量:

const root = document.documentElement
root.style.setProperty('--test-thing', "Hello World")

上面的CSS在所应用的元素(标签)上基本上可以正常工作,基本上只是一个白色正方形,但是当我尝试更新CSS变量--test-thing以通过{ {1}}道具,整个东西消失了。

使用伪元素或类不能做到这一点吗?

通过研究SO的相关文章,我的理解是,使用CSS变量可以做到这一点。

对于上下文,I’m working off this example是纯CSS交互式文件夹(当打开时是指我想动态地适当更新内容)。

1 个答案:

答案 0 :(得分:3)

好吧,我弄清楚了为什么会这样。仍然不是100%知道为什么,但这与新值不在引号中有关。只需将值放在引号中,它就可以正常工作。

const root = document.documentElement
root.style.setProperty('--test', "'Hello World'") // <-- this needs to be in quotes
:root {
  --test: "";
}

#test {
  height: 100px;
  width: 100px;
  background: #ccc;
}
#test:after {
  content: var(--test);
  min-width: 100px;
  background: #000;
  min-height: 30px;
  color: #fff;
}
<div id="test">

</div>