[英]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.