如何用js控制css伪类after

RT

如何用js控制css伪类after

阅读 66.8k
评论
    7 个回答
    • 8k

    SO 的答案沒有一個能像操縱普通 DOM 一樣操縱 pseudo element 的樣式。

    我做到了。

    點擊段落,由腳本切換 Section mark 的顏色:

    http://jsfiddle.net/s3fv8e5v/4/

    <!DOCTYPE html>
    <title>CSS</title>
    
    <style>
        body {
            font: 200%/1.45 charter;
        }
        ref::before {
            content: '\00A7';
            letter-spacing: .1em;
        }
    </style>
    
    <article>The seller can, under Business Law <ref>1782</ref>, offer a full refund to buyers. </article>
    
    <script>
        function ruleSelector(selector) {
            function uni(selector) {
                return selector.replace(/::/g, ':')
            }
            return Array.prototype.filter.call(Array.prototype.concat.apply([], Array.prototype.map.call(document.styleSheets, function(x) {
                return Array.prototype.slice.call(x.cssRules);
            })), function(x) {
                return uni(x.selectorText) === uni(selector);
            });
        }
    
        var toggle = false, 
            pseudo = ruleSelector("ref::before").slice(-1);
    
        document.querySelector("article").onclick = function() {
            pseudo.forEach(function(rule) {
                if (toggle = !toggle)
                    rule.style.color = "red";
                else
                    rule.style.color = "black";
            });
        }
    </script>
    
      相似问题
      推荐文章