JavaScript修改伪元素样式(pseudo element styles)

类似如下的CSS声明:

#progress {
    background: #333;
    border-radius: 13px;
    height: 10px;
    width: 300px;
    padding: 3px;
}

#progress:after {
    content: '';
    display: block;
    background: orange;
    width: 0%;
    height: 100%;
    border-radius: 9px;
}

HTML中的声明如下:

<div id="progress" style="text-align: center; margin-left: auto; margin-right: auto;"></div>

需要动态修改CSSwidth属性。
由于是伪元素样式,并不属于DOM对象,因此,我们没有办法直接通过JQuery来修改。

比较完美的解决方法如下:

定义如下函数,对样式表遍历,根据名称获取我们指定的样式对象

function getRuleWithSelector(selector) {
    var numSheets = document.styleSheets.length;
    var numRules;
    var sheetIndex;
    var ruleIndex;
    // Search through the style sheets.
    for (sheetIndex = 0; sheetIndex < numSheets; sheetIndex += 1) {
        numRules = document.styleSheets[sheetIndex].cssRules.length;
        for (ruleIndex = 0; ruleIndex < numRules; ruleIndex += 1) {
            if (document.styleSheets[sheetIndex].cssRules[ruleIndex].selectorText === selector) {
                return document.styleSheets[sheetIndex].cssRules[ruleIndex];
            }
        }
    }
    return null;
}

function isNull(arg) {
    return ((undefined == arg) || (null == arg) ||('' == arg));
}

使用时候的代码如下:

var afterRule = getRuleWithSelector("#progress::after");
if (true != isNull(afterRule)){
	afterRule.style.width = '20%';
}

参考链接


modify pseudo select :after in javascript

发布者

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注