为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

守候你守候我 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 关注
  • 215 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信