簡體   English   中英

如何在 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";

如果您使用 Chrome 作為網絡瀏覽器,則可以打開控制台並復制以下代碼:

document.getElementById("nav-questions").style.backgroundColor = "red"

然后你可以看到問題 Nav 的背景顏色發生了變化。 在此處輸入圖片說明

在此處輸入圖片說明

試試這個答案

 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM