js 操縱css僞元素 :after :before

寫在前面

導航條的下邊滑塊,本身是採用:before來寫,javascript

好處就是代碼比較工整好維護,可是因爲要求是可配置的因此不管滑塊的位置仍是寬度都須要更改僞元素才能夠,這直接css目前是沒辦法作到的css

ps: attr()目前瀏覽器只支持content屬性使用java

往body中嵌入css

var css = '._tab_index:before{content: " ";height: '+args.active.weight+';width: '+ms.itemWidth+'%;left: 0;'+set+';background: '+args.active.color+';position: absolute;}'
        	
// for (var i = ms.itemNum - 1; i >= 0; i--) {
// 	css+='._tab_index[active="'+i+'"]:before{left: '+i*ms.itemWidth+'%;}'
// }
$('<style>'+css+'</style>').appendTo('head');

這部分經過能夠經過改變active屬性來達到js操縱滑塊,可是因爲不是直接修改屬性,若是要有無極的效果,則還須要想辦法segmentfault

從新編寫選擇器

參考:http://jsfiddle.net/s3fv8e5v/4/
       :https://segmentfault.com/q/1010000002452755瀏覽器

//用於僞類選擇
ruleSelector:function(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);
    });
},

//設置滑塊
setBlock:function(num){
    var Block = this.ruleSelector("._tab_index::before").slice(-1);
    Block.forEach(function(rule) {
        rule.style.left = num;
    })
},
相關文章
相關標籤/搜索