我有一個導航欄,其中每個按鈕更改身體的背景。他們每個人都改變它不同的顏色。我已經爲每個按鈕創建了onmouseover
和onmouseout
函數來實現此目的。但是,我想知道是否有辦法通過僅僅通過它們的類來引用它們來編寫每個函數中的一個?他們都有相同的button
。函數可以應用於某個類的所有元素嗎?我的代碼:JavaScript函數可以應用於某個CSS類的所有元素嗎?
function whichButton(x) {
if (x==1)
return "red";
if (x==2)
return "green";
if (x==3)
return "blue";
if (x==4)
return "orange";
if (x==0)
return initBG;
}
button1.onmouseover = function() {
document.body.style.backgroundColor = whichButton(1);
}
button1.onmouseout = function() {
document.body.style.backgroundColor = whichButton(0);
}
button2.onmouseover = function() {
document.body.style.backgroundColor = whichButton(2);
}
button2.onmouseout = function() {
document.body.style.backgroundColor = whichButton(0);
}
button3.onmouseover = function() {
document.body.style.backgroundColor = whichButton(3);
}
button3.onmouseout = function() {
document.body.style.backgroundColor = whichButton(0);
}
button4.onmouseover = function() {
document.body.style.backgroundColor = whichButton(4);
}
button4.onmouseout = function() {
document.body.style.backgroundColor = whichButton(0);
}
initBG
只是保存了頁面的初始背景。
我已經試過這樣:
document.getElementsByClassName('button').onmouseover = function() {
document.body.style.backgroundColor = whichButton(1);
}
,但它不會觸發功能。我想這樣做,我也需要有一種方法來讀取元素的ID作爲一個字符串,所以我可以得到它的數字...
這是更多的好奇心比必要性,只是試圖想辦法讓我的代碼變小!我可以看到這在許多應用程序中很有用,所以我很想了解更多信息!
對應的HTML:
<div id="navbar">
<p id="button1" class="button">Red</p><p id="button2" class="button">Blue</p><p id="button3" class="button">Green</p><p id="button4" class="button">Orange</p>
</div>
將事件監聽器綁定到文檔並檢查回調中的目標 – PeeHaa
請首先添加相關的html請 –
您有三個不同的函數..但是您要求如何將相同的函數應用於所有按鈕?我在這裏迷路了..請讓需求更清楚 –