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

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

如何使按鈕在單擊時更改背景和文本顏色

如何使按鈕在單擊時更改背景和文本顏色

守候你守候我 2021-11-12 10:54:52
我正在嘗試創建一個按鈕來更改整個頁面的背景顏色和一些文本顏色,但我無法使其工作。背景目前正在工作,但文本不會改變顏色。我希望“changeText”影響類而不是 Id。我對 JavaScript 的了解為零,所以很難知道出了什么問題。這是代碼:var colors = ["green", "red", "blue"];var colorIndex = 0;function changeText() {  var col = document.getElementsByClassname("textcolor");  if (colorIndex >= colors.length) {    colorIndex = 0;  }  col.body.style.color = colors[colorIndex];  colorIndex++;}var colors = ["red", "blue", "green"];var colorIndex = 0;function changeBackground() {  var col = document.getElementById("bodycolor");  if (colorIndex >= colors.length) {    colorIndex = 0;  }  col.style.backgroundColor = colors[colorIndex];  colorIndex++;}<body id='bodycolor'>  <h1 class="textcolor">Title Color Change</h1><br>  <p class="textcolor">Text Color Change </p><br>  <button type="button" onclick="changeBackground();changeText();">Click me</button></body>
查看完整描述

3 回答

?
汪汪一只貓

TA貢獻1898條經驗 獲得超8個贊

背景更改有效,因為 getElementById 只返回一個可以設置樣式屬性的元素。


getElementsByClassName() 但是返回一個項目集合。您將不得不迭代它并更改每個元素的樣式元素。嘗試這個:


function changeText() {

  var col = document.getElementsByClassName("textcolor");

  if (colorIndex >= colors.length) {

    colorIndex = 0;

  }

for(var i = 0; i < col.length; i++){

  col[i].style.color = colors[colorIndex];

}

  colorIndex++;

}

此外,您不需要 .body 來設置樣式。


查看完整回答
反對 回復 2021-11-12
?
海綿寶寶撒

TA貢獻1809條經驗 獲得超8個贊

你為什么不給它唯一的 ID 并檢查它


  let colors = ["green", "red", "blue"];

    let colorIndex = 0;


    function changeBackground() {

      let col = document.getElementById("bodycolor");

      if (colorIndex >= colors.length) {

        colorIndex = 0;

      }

      col.style.backgroundColor = colors[colorIndex];

      colorIndex++;


       let h1Color = document.getElementById("h1Color")

       let pColor = document.getElementById("pColor");


      if (colorIndex >= colors.length) {

        colorIndex = 0;

      }

      h1Color.style.color = colors[colorIndex];

      pColor.style.color = colors[colorIndex];

     colorIndex++;

    }

 <body id='bodycolor'>

      <h1 id="h1Color">Title Color Change</h1><br>

      <p id="pColor">Text Color Change </p><br>

      <button type="button" onclick="changeBackground()">Click me</button>

    </body>


查看完整回答
反對 回復 2021-11-12
?
飲歌長嘯

TA貢獻1951條經驗 獲得超3個贊

getElementsByClassName 返回包含提到的類名的所有元素的數組

嘗試

col[0].style.color = colors[colorIndex];

這是您的工作示例

訪問https://codepen.io/vikas_saini/pen/jOOErNZ


查看完整回答
反對 回復 2021-11-12
  • 3 回答
  • 0 關注
  • 259 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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