javascript 通过onclick函数更改用js插入DOM的div的颜色

gr8qqesn  于 2022-12-17  发布在  Java
关注(0)|答案(2)|浏览(131)

我是javascript的新手,我想做下一件事,当点击按钮时,它会根据先前的值将变量“value”的值更改为true或false,并根据该值更改文本的背景色,但我看不到任何变化!

let value = true
const container = document.querySelector(".container")
let color = " "

function changeColor() {
  value = !value
  console.log(value)
  if (value) {
    color = "background-color:purple"
  } else {
    color = " "
  }

  console.log(color)
}

container.innerHTML = `<div style= ${color} >This is a TEST</div>`
body {
  font-size: 2rem;
  font-weight: 900;
}

.container {
  border: 5px solid;
  width: 250px;
  height: 100px;
}
<div class="container"></div>
<button onclick="changeColor()">Click</button>
6ss1mwsb

6ss1mwsb1#

这个问题已经得到了回答,但我想帮助您理解为什么它不起作用。
当你设置html内容并使用一个模板文字(反勾号和${})时,你好像是在将html字符串设置为<div style=background-color:purple;></div>。Html属性需要引号才能工作,所以解决方案可能如下所示:

container.innerHTML = `<div style="${color}">This is a TEST</div>`

第二,设置容器的innerHTML的语句在函数之外,所以它只在页面第一次加载时运行一次,将它移到函数内部可以解决这个问题。
现在,一切都应该正常了,我创建了一个jsfiddle来展示您希望它工作的方式:https://jsfiddle.net/ahpw07uf/
为了便于以后参考,使用element.style.backgroundColor = "purple"(它会自动将background-color: purple;添加到元素的style属性中)或切换上述类要容易得多。

cngwdvgl

cngwdvgl2#

关键问题是,一旦将元素添加到容器中,就不能再影响style属性,除非再次从DOM中拾取该元素。
另一个问题是,您应该在进行更改 * 之后 * 重置value变量:

let value = true
const container = document.querySelector(".container")
let color = "";

function changeColor() {

  // Pick up the element from the DOM
  const inner = container.querySelector('div');

  // Update the style
  if (value) {
    inner.style = "background-color:purple"
  } else {
    inner.style = "";
  }

  // Now update the value
  value = !value

}

container.innerHTML = `<div style= ${color} >This is a TEST</div>`
body {
  font-size: 2rem;
  font-weight: 900;
}

.container {
  border: 5px solid;
  width: 250px;
  height: 100px;
}
<div class="container"></div>
<button onclick="changeColor()">Click</button>

toggle类的开/关可能比依赖变量来更新样式更容易。
1.我已经删除了内联JS,并将一个event listener附加到该按钮,并将一个类添加到附加的div元素。
1.当click事件被触发时,changeColor函数被调用,我们可以通过容器得到inner元素,然后在每次单击时切换元素的classList上的purple类。
一个一个三个一个一个一个一个一个四个一个一个一个一个一个五个一个

相关问题