跳轉到內容

JavaScript/更改元素樣式

來自華夏公益教科書



正如您在前面的章節中所看到的,元素的屬性可以透過 JavaScript 進行修改。兩個屬性,classstyle,會影響元素的視覺表示。它們包含 CSS 程式碼。

<!DOCTYPE html>
<html>
<head>
  <script>
  function toggle() {
    "use strict";
    // ...
  }
  </script>
<style>
  .divClassGreen {
    background-color: green;
    padding: 2em;
    margin: 1em
  }
  .divClassRed {
    background-color: red;
    padding: 2em;
    margin: 1em
  }
</style>
</head>

<body id="body">
  <div id="div_1" class="divClassGreen">A DIV element</div>
  <div id="div_2" style="background-color: blue; padding: 2em; margin: 1em">Another DIV element</div>
  <button id="buttonToggle" onclick="toggle()" style="margin:1em 0em 1em 0em">Start</button>
</body>
</html>

class 屬性標識在 HTML 的 style 元素中建立的 CSS 類。style 屬性定義內聯(本地)的 CSS 規則。

要修改它們,像處理任何其他 屬性 一樣處理它們。它們沒有特殊的規則或例外。

一個例子

[編輯 | 編輯原始碼]

我們使用上面的 HTML 檔案;只有 JavaScript 函式發生了變化。當按鈕被點選時,該函式將 CSS 類 'divClassRed' 分配給 'div_1',並將 'div_2' 的內聯 'style' 屬性更改為不同的值。

  function toggle() {
    "use strict";

    // locate the elements to be changed  
    const div_1 = document.getElementById("div_1");
    const div_2 = document.getElementById("div_2");

    // modify its 'class' attribute
    div_1.setAttribute("class", "divClassRed");
 
    // an 'inline' modification
    div_2.setAttribute("style", "background-color: silver; padding: 4em; margin: 2em");
    //or: div_2.style = "background-color: silver; padding: 4em; margin: 2em";
  }

'style' 屬性在其自身的屬性中儲存 CSS 屬性,如 'color' 或 'padding'。這與一般的 JavaScript 物件規則相關。因此,以下語法等同於前面的 div_2.setAttribute 呼叫。

  div_2.style.backgroundColor = "silver"; // see below: camel-case
  div_2.style.padding = "4em";
  div_2.style.margin = "2em";

'style' 的屬性

[編輯 | 編輯原始碼]

在 CSS 中,一些屬性在它們的名稱中定義了一個連字元,例如 'background-color' 或 'font-size'。當您在 JavaScript 中以 style 的屬性 的語法使用它們時,名稱會略有變化。連字元後的字元必須用大寫字母書寫,連字元消失:'style.backgroundColor' 或 'style.fontSize'。這被稱為 駱駝式命名法

div_1.style.fontSize = "2em"; // the font's size as property of 'style'
/*
The next line would run into a syntax error because the hyphen
would be interpreted as a minus operation.
div_1.style.font-size = "2em";
*/

所有其他在 CSS 中出現此類名稱的地方都不會改變。特別是 HTML <style> 元素內部顯示的連字元語法,以及內聯定義形式的使用保持不變。

... 可在另一個頁面上獲得(點選此處)。
華夏公益教科書