[英]How to change the color of navigation bar using a button click in javascript?
[英]How to change the color of the navigation bar in Javascript?
你可以在你的按鈕上添加一個監聽器,當你按下它時,改變它的顏色。 例如,您可以這樣做:
var button = document.getElementById('myButton');
button.addEventListener('click', function(e) {
button.style.backgroundColor = "red";
});
您還可以更改按鈕的 CSS 類,而不是直接使用 javascript 更改其顏色:
var button = document.getElementById('myButton');
button.addEventListener('click', function(e) {
button.className = 'selected';
});
CSS :
.selected
{
background-color: red;
}
你可以用這樣的 javascript 來做到這一點:
document.getElementById("elementId").style.backgroundColor = "blue";
試試這個答案
function getElementById_Click() { document.getElementById("example").style.backgroundColor = "red"; } function getElementsByClassName_Click() { document.getElementsByClassName("example")[2].style.backgroundColor = "red"; }
<!DOCTYPE html> <html> <head> <style> .example, #example { border: 1px solid black; margin: 5px; } </style> </head> <body> <div class="example "> This is getElementsByClassName Example 1 </div> <div id="example"> This is getElementById Example </div> <div class="example"> This is getElementsByClassName Example 2 </div> <div class="example"> This is getElementsByClassName Example 3 </div> <div class="example"> This is getElementsByClassName Example 4 </div> <button type="button" onclick="getElementById_Click()" >GET ELEMENT BY ID</button> <button type="button" onclick="getElementsByClassName_Click()" >GET ELEMENT BY CLASS</button> </body> </html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.