search

Home  >  Q&A  >  body text

javascript - 如何用js控制css伪类after

RT

如何用js控制css伪类after

大家讲道理大家讲道理2940 days ago657

reply all(6)I'll reply

  • 怪我咯

    怪我咯2017-04-10 14:57:24

    像正常那样拿到伪类这个DOM估计是不大可能了,不过控制的方法也有很多,你可以参考一下。

    http://stackoverflow.com/questions/5041494/manipulating-css-pseudo-elements-such-as-before-and-after-using-jquery
    http://stackoverflow.com/questions/9798210/is-there-any-way-to-reset-after-before-css-rules-for-an-element

    reply
    0
  • PHP中文网

    PHP中文网2017-04-10 14:57:24

    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>
    

    reply
    0
  • 迷茫

    迷茫2017-04-10 14:57:24

    为什么不能控制?

    <style>
    p:after{content:'我是后缀'}
    </style>
    <p>正文内容</p>
    
    <script>
    var css=function(t,s){
        s=document.createElement('style');
        s.innerText=t;
        document.body.appendChild(s);
    };
    
    document.onclick=function(){
        css('p:after{content:\'修改一下\'}');
    };
    </script>
    

    reply
    0
  • ringa_lee

    ringa_lee2017-04-10 14:57:24

    首先after是伪元素,不是伪类。
    其次是可以js改变它的样式的,操作思路是js更改style代码,而不是js选中元素再更改样式,具体你可以看看这个
    http://pankajparashar.com/posts/modify-pseudo-elements-css/

    reply
    0
  • 怪我咯

    怪我咯2017-04-10 14:57:24

    这个问题我思考过,既然我们不能直接控制伪类,那么我们换个思路,控制伪类的父级,可以改变这个父级的class,再在这个class下面用样式控制伪类。

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-10 14:57:24

    点个赞也需要声望,我也是醉...

    reply
    0
  • Cancelreply