2 回答

TA貢獻1808條經(jīng)驗 獲得超4個贊
是否可以用一些 javascript 來做我想做的事情?我的意思是,是否可以循環(huán)當前頁面的 css 規(guī)則并向每個選擇器規(guī)則添加字符串“#idOfElement”?
是的。使用 javascript,您可以訪問和修改樣式表的內(nèi)容。例如,如果您只有一個StyleSheet,您可以像這樣引用它:
document.styleSheets[0]
每個StyleSheet都有一個CSSRuleList- 一個類似數(shù)組的對象,其中包含有序的對象集合CSSRule:
document.styleSheets[0].cssRules
每個CSSRule屬性中都有一個selectorText屬性。
因此,如果您想引用第selectorText一個的 CSSRule第一個 StyleSheet,您可以使用:
document.styleSheets[0].cssRules[0].selectorText // .selector1
工作示例:
const myCSSRules = document.styleSheets[0].cssRules;
for (let CSSRule of myCSSRules) {
CSSRule.selectorText = '#my-element ' + CSSRule.selectorText;
console.log(CSSRule.selectorText);
}
.selector1 {
color: red;
font-weight: 700;
}
.selector2 {
color: blue;
font-weight: 700;
}
<p class="selector1">Selector 1</p>
<p class="selector2">Selector 2</p>
<div style="border: 1px dashed red; text-align:center;" id="my-element">
<p class="selector1">Selector 1</p>
<p class="selector2">Selector 2</p>
</div>

TA貢獻1772條經(jīng)驗 獲得超5個贊
document.head.removeChild()可以使用和方法動態(tài)刪除或添加 CSS document.head.appendChild()。
要即時刪除現(xiàn)有的 css 文件:
var redTheme = document.getElementById('red-theme-css')
document.head.removeChild(redTheme)
要動態(tài)添加新的 css 文件:
var blueTheme = document.createElement('link')
blueTheme.id = "blue-theme-css"
blueTheme.type = "text/css"
blueTheme.rel = "stylesheet"
blueTheme.href = "link-to-blue-theme-css-file"
document.head.appendChild(blueTheme)
上述方法可用于更改整個文檔或特定組件的主題。
如果要求僅更改一個組件的樣式,則要加載的 css 文件必須以這樣的方式編寫:它具有僅適用于特定組件的類。
添加回答
舉報