在開發(fā)一個ui編輯功能巡验,因為使用的是Vue辫封,最開始的時候是的方法是直接將styles放在dom元素上面砖第,當(dāng)遇到偽元素就無計可施了(切沒發(fā)現(xiàn)JS直接獲取DOM偽元素的方法)荷腊。
于是就想能不能使用什么方法設(shè)置一段css樣式
網(wǎng)絡(luò)上的辦法
我們可以這樣:
document.styleSheets[0].insertRule('.test::before{color:green}',0)//chrome,firefox,ie9+,Edge,移動端
// 不推薦使用绍移,實際使用過程中未生效
document.styleSheets[0].addRule('.test::before{color:green}',0)// IE 瀏覽器
我們還可以這樣:
var style=document.createElement('style');
style.innerHTML=".test::before{color:green}";
document.head.appendChild(style);
我是在移動端使用的悄窃,實際上這兩種方法都是可以的,但是我選擇使用第二種登夫,因為兼容性更好
解決兼容問題
對于兼容問題MDN上面已經(jīng)給出了一個答案 https://developer.mozilla.org/zh-CN/docs/Web/API/CSSStyleSheet/insertRule
(function(Sheet_proto){
var originalInsertRule = Sheet_proto.insertRule;
if (originalInsertRule.length === 2){ // 2 個托管參數(shù): (selector, rules)
Sheet_proto.insertRule = function(selectorAndRule){
// 首先广匙,從規(guī)則中分離選擇器
a: for (var i=0, Len=selectorAndRule.length, isEscaped=0, newCharCode=0; i !== Len; ++i) {
newCharCode = selectorAndRule.charCodeAt(i);
if (!isEscaped && (newCharCode === 123)) { // 123 = "{".charCodeAt(0)
// 其次,找到花括號
var openBracketPos = i, closeBracketPos = -1;
for (; i !== Len; ++i) {
newCharCode = selectorAndRule.charCodeAt(i);
if (!isEscaped && (newCharCode === 125)) { // 125 = "}".charCodeAt(0)
closeBracketPos = i;
}
isEscaped ^= newCharCode===92?1:isEscaped; // 92 = "\\".charCodeAt(0)
}
if (closeBracketPos === -1) break a; // No closing bracket was found!
/*else*/ return originalInsertRule.call(
this, // 想要改變的樣式表
selectorAndRule.substring(0, openBracketPos), // 選擇器
selectorAndRule.substring(closeBracketPos), // 規(guī)則
arguments[3] // 插入的索引
);
}
// Works by if the char code is a backslash, then isEscaped
// gets flipped (XOR-ed by 1), and if it is not a backslash
// then isEscaped gets XORed by itself, zeroing it
isEscaped ^= newCharCode===92?1:isEscaped; // 92 = "\\".charCodeAt(0)
}
// Else, there is no unescaped bracket
return originalInsertRule.call(this, selectorAndRule, "", arguments[2]);
};
}
})(CSSStyleSheet.prototype);
這段代碼應(yīng)該放在何處才能生效恼策,可以自己思考一下鸦致,至于是否選擇這個兼容方案大家自己選擇。
插入順序問題
這兩個方法因為都是插入了一段CSS代碼涣楷,CSS在解析的時候會根據(jù)引入的先后順序和權(quán)重值來解析分唾,導(dǎo)致我們插入的代碼被覆蓋,雖然第二種方法是插入到了head最后狮斗,一定程度上避免了這種問題绽乔,但是不能完全解決這種隱患
解決辦法就是當(dāng)發(fā)現(xiàn)或者憑經(jīng)驗判斷樣式未生效,需要在當(dāng)前功能執(zhí)行之后在head最后重新添加對應(yīng)的CSS代碼
刪除無效CSS代碼
- 對于第一種方法
CSSStyleSheet.deleteRule() 移除指定的CSS代碼 - 對于第二種方法
可以在創(chuàng)建style
的時候設(shè)置一個id碳褒,可以使用document.styleSheet
來匹配id折砸,可以是移除dom或者使用 CSSStyleSheet.deleteRule()移除指定的CSS代碼
參考地址
DocumentOrShadowRoot.styleSheets
Document.styleSheetSets
CSSStyleSheet
CSSStyleSheet.insertRule()
Document.createElement()
使用 js 設(shè)置偽元素樣式
JavaScript HTML DOM - 改變 CSS
JS addRule()和insertRule()方法:添加CSS樣式
如何使用JS操縱偽元素
Js動態(tài)加載CSS樣式文件的2種方法