如何使用 JavaScript 建立 style 標籤?


JavaScript 允許開發者建立和操作 style 標籤,以改變網頁的外觀。透過使用document.createElement() 方法、.sheet 屬性以及.insertRule().deleteRule() 方法,我們可以向樣式表中新增、修改和刪除 CSS 規則。透過將這些技術與事件監聽器結合使用,我們可以建立動態和互動式的網頁,這些網頁可以根據使用者互動改變其外觀。

JavaScript 最強大的功能之一是能夠操作 DOM(文件物件模型),也就是網頁的結構。操作 DOM 的一種方法是使用 JavaScript 建立和修改 style 標籤。在這篇博文中,我們將介紹使用 JavaScript 建立 style 標籤的不同方法,以及如何使用它來更改網頁的外觀。

建立 Style 標籤

在 JavaScript 中構造 style 標籤最常用的方法是使用document.createElement() 方法,當然還有其他方法,例如createElement() 方法。此函式只接受一個引數:我們要建立的元素的標籤名稱。在這種情況下,因為我們要新增一個 style 標籤,所以引數應該是“style”。

// create a new style tag
var style = document.createElement("style");

建立 style 標籤後,我們可以使用document.head.appendChild() 方法將其新增到文件的頭部。

// add the style tag to the head of the document
document.head.appendChild(style);

或者,我們也可以使用 innerHTML 屬性在一行程式碼中建立 style 標籤並將其新增到文件的頭部。

// create and add a new style tag to the head of the document
document.head.innerHTML += "<style></style>";

更新樣式

建立 style 標籤後,我們可以使用.sheet 屬性訪問樣式表物件,並使用.insertRule() 方法向其中新增新的 CSS 規則。.insertRule() 方法接受兩個引數:第一個是要新增的 CSS 規則,第二個是要插入規則的索引。如果不指定索引,則規則將新增到樣式表的末尾。

// add a new CSS rule to the stylesheet
style.sheet.insertRule("body { background-color: red; }", 0);

您也可以使用.append() 方法一次新增多個 CSS 規則。

// add multiple CSS rules to the stylesheet
style.sheet.append("body { background-color: red; }");
style.sheet.append("h1 { color: white; }");

更改現有樣式

我們可以使用 styleSheet 物件的.cssText 屬性更改現有樣式。

// change the existing styles
style.sheet.cssText = "body { background-color: blue; }";

移除樣式

要移除特定的 CSS 規則,我們可以使用.deleteRule() 方法。此方法接受一個引數,即要移除的規則的索引。

style.sheet.deleteRule(0);

要移除所有 CSS 規則,我們可以使用 .cssText 屬性。

// remove all the CSS rules
style.sheet.cssText = "";

示例

假設我們希望在單擊按鈕時更改網頁的背景顏色。我們可以建立一個 style 標籤,並新增一個 CSS 規則來使用以下程式碼更改背景顏色:

<html>
<head>
   <script>      
      // get the button element when the DOM is loaded
      var style = document.createElement("style");
      document.head.appendChild(style);
      style.sheet.insertRule("body { background-color: red; }", 0);
      document.addEventListener("DOMContentLoaded", function() {
         var button = document.getElementById("changeColor");
         
         // add an event listener to the button
         button.addEventListener("click", function() {
            
            // change the background color of the body
            document.body.style.backgroundColor = "blue";
         });
      });
   </script>
</head>
<body>
   <button id="changeColor">Change Color</button>
</body>
</html>

在這個例子中,我們首先建立一個新的 style 標籤並將其新增到文件的頭部。然後,我們新增一個 CSS 規則,將正文的背景顏色更改為紅色。單擊按鈕時,我們將使用 .cssText 屬性將正文的背景顏色更改為藍色。

更新於:2023年3月2日

7000+ 次瀏覽

啟動您的職業生涯

完成課程後獲得認證

開始學習
廣告