我是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>
2条答案
按热度按时间6ss1mwsb1#
这个问题已经得到了回答,但我想帮助您理解为什么它不起作用。
当你设置html内容并使用一个模板文字(反勾号和${})时,你好像是在将html字符串设置为
<div style=background-color:purple;></div>
。Html属性需要引号才能工作,所以解决方案可能如下所示:第二,设置容器的innerHTML的语句在函数之外,所以它只在页面第一次加载时运行一次,将它移到函数内部可以解决这个问题。
现在,一切都应该正常了,我创建了一个jsfiddle来展示您希望它工作的方式:https://jsfiddle.net/ahpw07uf/
为了便于以后参考,使用
element.style.backgroundColor = "purple"
(它会自动将background-color: purple;
添加到元素的style属性中)或切换上述类要容易得多。cngwdvgl2#
关键问题是,一旦将元素添加到容器中,就不能再影响
style
属性,除非再次从DOM中拾取该元素。另一个问题是,您应该在进行更改 * 之后 * 重置
value
变量:toggle
类的开/关可能比依赖变量来更新样式更容易。1.我已经删除了内联JS,并将一个event listener附加到该按钮,并将一个类添加到附加的
div
元素。1.当click事件被触发时,
changeColor
函数被调用,我们可以通过容器得到inner
元素,然后在每次单击时切换元素的classList
上的purple
类。一个一个三个一个一个一个一个一个四个一个一个一个一个一个五个一个