亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 javascript 覆蓋 css 文件的“動態”CSS 規則選擇器

使用 javascript 覆蓋 css 文件的“動態”CSS 規則選擇器

蕭十郎 2023-09-21 17:19:52
我有一個包含選擇標簽的頁面,該標簽允許使用一些javascript“動態”更改頁面的css 主題。現在,我想允許更改頁面中特定 html 元素的 css 樣式。例如,我有兩個“主題”樣式表:/* in red theme file 'theme_red.css' */.title{color:red;}.text{...}/* in blue theme file 'theme_blue.css' */.title{color:blue;}.text{...}我在頁面中有一些“選擇”標簽“更改主題”。這是一個極簡的例子,在實際情況中,“主題”html 元素的數量和樣式表的數量是模塊化的。我正在尋找創建一個像這樣的javascript函數:(純javascript ES6)loadCssThemeFileOnTheFlyForSpecificHtmlElement(idOfSpecificHtmlElement, themeName){    // 1) Insert a new link tag in the head of the page with href attribute "themeName + '.css'"    ...    // 2) for each css rules selector (of the css file ?), override the css selector rule like this :     // `.selector1` become `#idOfElement .selector1`    // `.selector2` become `#idOfElement .selector2`    // ...    // `.selectorN` become `#idOfElement .selectorN`}我陷入了函數的第2步insertCssFileOnTheFly。是否可以用一些 javascript 來做我想做的事情?我的意思是,是否可以循環當前頁面的 css 規則并向每個選擇器規則添加字符串“#idOfElement”?
查看完整描述

2 回答

?
炎炎設計

TA貢獻1808條經驗 獲得超4個贊

是否可以用一些 javascript 來做我想做的事情?我的意思是,是否可以循環當前頁面的 css 規則并向每個選擇器規則添加字符串“#idOfElement”?


是的。使用 javascript,您可以訪問和修改樣式表的內容。例如,如果您只有一個StyleSheet,您可以像這樣引用它:


document.styleSheets[0]

每個StyleSheet都有一個CSSRuleList- 一個類似數組的對象,其中包含有序的對象集合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>


查看完整回答
反對 回復 2023-09-21
?
月關寶盒

TA貢獻1772條經驗 獲得超5個贊

document.head.removeChild()可以使用和方法動態刪除或添加 CSS document.head.appendChild()。


要即時刪除現有的 css 文件:


var redTheme = document.getElementById('red-theme-css')

document.head.removeChild(redTheme)

要動態添加新的 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 文件必須以這樣的方式編寫:它具有僅適用于特定組件的類。

查看完整回答
反對 回復 2023-09-21
  • 2 回答
  • 0 關注
  • 138 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號