猿问

如何使按钮在单击时更改背景和文本颜色

我正在尝试创建一个按钮来更改整个页面的背景颜色和一些文本颜色,但我无法使其工作。


背景目前正在工作,但文本不会改变颜色。我希望“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>


守候你守候我
浏览 216回答 3
3回答

汪汪一只猫

背景更改有效,因为 getElementById 只返回一个可以设置样式属性的元素。getElementsByClassName() 但是返回一个项目集合。您将不得不迭代它并更改每个元素的样式元素。尝试这个:function changeText() {&nbsp; var col = document.getElementsByClassName("textcolor");&nbsp; if (colorIndex >= colors.length) {&nbsp; &nbsp; colorIndex = 0;&nbsp; }for(var i = 0; i < col.length; i++){&nbsp; col[i].style.color = colors[colorIndex];}&nbsp; colorIndex++;}此外,您不需要 .body 来设置样式。

海绵宝宝撒

你为什么不给它唯一的 ID 并检查它&nbsp; let colors = ["green", "red", "blue"];&nbsp; &nbsp; let colorIndex = 0;&nbsp; &nbsp; function changeBackground() {&nbsp; &nbsp; &nbsp; let col = document.getElementById("bodycolor");&nbsp; &nbsp; &nbsp; if (colorIndex >= colors.length) {&nbsp; &nbsp; &nbsp; &nbsp; colorIndex = 0;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; col.style.backgroundColor = colors[colorIndex];&nbsp; &nbsp; &nbsp; colorIndex++;&nbsp; &nbsp; &nbsp; &nbsp;let h1Color = document.getElementById("h1Color")&nbsp; &nbsp; &nbsp; &nbsp;let pColor = document.getElementById("pColor");&nbsp; &nbsp; &nbsp; if (colorIndex >= colors.length) {&nbsp; &nbsp; &nbsp; &nbsp; colorIndex = 0;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; h1Color.style.color = colors[colorIndex];&nbsp; &nbsp; &nbsp; pColor.style.color = colors[colorIndex];&nbsp; &nbsp; &nbsp;colorIndex++;&nbsp; &nbsp; }&nbsp;<body id='bodycolor'>&nbsp; &nbsp; &nbsp; <h1 id="h1Color">Title Color Change</h1><br>&nbsp; &nbsp; &nbsp; <p id="pColor">Text Color Change </p><br>&nbsp; &nbsp; &nbsp; <button type="button" onclick="changeBackground()">Click me</button>&nbsp; &nbsp; </body>

饮歌长啸

getElementsByClassName 返回包含提到的类名的所有元素的数组尝试col[0].style.color&nbsp;=&nbsp;colors[colorIndex];这是您的工作示例访问https://codepen.io/vikas_saini/pen/jOOErNZ
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答