[英]JavaScript for changing a <div> colour from a button press
当我的 html 和 JS 代码在同一个文件中时,我有点不确定为什么我的代码似乎不起作用。 当 html 和 JS 分开时,似乎工作正常。 有人可以指出我的错误....我是新手!
HTML:
<div class="main">
<div class="light"></div>
<button onclick="chngCol()" id="burn">Burn!</button>
</div>
JavaScript:
chngCol() {
if(document.getElementByClass('light').style.background == "#00ffff")
{
document.getElementByClass('light').style.background = "#ffff00";
}
else if(document.getElementByClass('light').style.background == "ffff00")
{
document.getElementByClass('light').style.background = "#ff00ff";
}
else if(document.getElementByClass('light').style.background == "#ff00ff")
{
document.getElementByClass('light').style.background = "#00ffff";
}
}
CSS:
.light{
width: 50px;
height: 50px;
background-color:#00ffff;
}
所有代码都在同一个文档中,带有适当的标签,但是我在第一个 { 调用 chngCol.
有很多问题。
chngCol() {
不是有效的 JS。 function chngCol() {
或const chngCol = () =>
document.getElementsByClassName("light")[0]
或者更好的是document.querySelector(".light")
我认为您打算这样做:
let cnt = 0; const colors = ["#00ffff", "#ffff00", "#ff00ff"]; const chngCol = () => { cnt++; if (cnt >= colors.length) cnt = 0; // wrap document.querySelector('.light').style.background = colors[cnt]; // use the array } document.getElementById("burn").addEventListener("click", chngCol);
.light { width: 50px; height: 50px; background-color: #00ffff; } #burn { width: 150px; font-weight: 700; }
<div class="main"> <div class="light"></div> <button id="burn">Burn!</button> </div>
document.getElementByClass 选择器是一个数组选择器。 为了 select 你的元素你应该 select 数组的第一个元素。 试试这个:
document.getElementsByClassName('light')[0].style.background
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.