跳至內容

JavaScript/更改元素樣式/練習

來自 WikiBooks,開放的世界開放的書籍

主題:CSS 樣式

我們使用前一頁的 HTML 頁面作為練習。



1. 修改函式 toggle

  • 如果 'div_1' 的背景顏色為綠色,則將其更改為水綠色;否則,將其更改回綠色。
  • 如果按鈕的背景顏色為紅色,則將其更改為黃色;否則,將其更改回紅色。
單擊以檢視解決方案
function toggle() {
  "use strict";

  // locate div_1
  const div_1 = document.getElementById("div_1");
  if (div_1.style.backgroundColor !== "aqua") {
    div_1.style.backgroundColor = "aqua";
  } else {
    div_1.style.backgroundColor = "green";
  }

  // locate the button
  const button = document.getElementById("buttonToggle");
  if (button.style.backgroundColor !== "red") {
    button.style.backgroundColor = "red";
  } else {
    button.style.backgroundColor = "yellow";
  }
}



2. 發揮創造力。修改函式 toggle,以便更改其他 CSS 屬性,例如,div 的文字大小、body 的內邊距或背景顏色,...



3. 修改函式 toggle

  • 詢問使用者 prompt() 他更喜歡哪個背景顏色作為第一個 div。
  • 將第一個 div 的背景顏色更改為此顏色。
單擊以檢視解決方案
function toggle() {
  "use strict";

  // locate div_1
  const div_1 = document.getElementById("div_1");
  
  // ask the user
  const tmp = prompt("What color do you prefer?");

  // change the color (if possible)
  div_1.style.backgroundColor = tmp;
}
華夏公益教科書