JavaScript:改变CSS Pseudo的任何机会或替代方案:之前和之后?

时间:2013-11-07 15:54:47

标签: javascript css pseudo-element

现在感觉我已经阅读了几乎整个stackoverflow论坛,找到任何改变伪元素的解决方案:after和:before。

根据我的理解:它无法更改,因为当浏览器显示它时,它不在DOM中。但它在哪里呢?在浏览器内存???

没关系,似乎无法使用:after /:before。

来获取伪元素

所以我尝试了另一种方式:

// read CSS value      
var color = window.getComputedStyle(document.querySelector('.myCssClass'), ':before').getPropertyValue('background-color');
// write CSS value
window.getComputedStyle(document.querySelector('.myCssClass'), ':before').setProperty('background-color', "#FF0000");

但是......浏览器不会感到高兴,而是返回:

NoModificationAllowedError: Modifications are not allowed for this document

OMG !!! 所以似乎没有改变这些事情的解决方法。

现在我的大问题是: 还有其他任何方式使用CSS来实现创建一个额外的类,其行为类似于:after /:before? 我试过了,但结果完全不同。

1 个答案:

答案 0 :(得分:3)

您可以使用:before:after定义类(例如下面的示例)。浏览器还可以通过类似于数组的document.styleSheets使样式表可用。每张表都包含规则(根据浏览器,它们位于属性rulescssRules上)。规则可以修改。

但这比在样式表中定义它然后使用类来操作它更麻烦:

.foo:before {
    content: "before foo ";
}
.bar:before {
    content: "before bar ";
}

然后,例如,这个HTML:

<div class="foo">there is stuff</div>

看起来像这样:

before foo there is stuff

然后你可以改变它:

document.querySelector(".foo").className = "bar";

它变成了:

before bar there is stuff

Live Example | Source