简体   繁体   English

如何在 Javascript 中更改导航栏的颜色?

[英]How to change the color of the navigation bar in Javascript?

Like in the stack overflow navigation bar喜欢在堆栈溢出导航栏中

if i click on questions the color of it should be change instead of orange line..如果我点击问题它的颜色应该改变而不是橙色线..

can anyone help?有人可以帮忙吗? 颜色变化

You can add a listener on your button, and when you press it, change the color of it.你可以在你的按钮上添加一个监听器,当你按下它时,改变它的颜色。 You can do this for example :例如,您可以这样做:

var button = document.getElementById('myButton');
button.addEventListener('click', function(e) { 
  button.style.backgroundColor = "red";
});

You can also change the CSS class of your button instead of changing its color directly with javascript :您还可以更改按钮的 CSS 类,而不是直接使用 javascript 更改其颜色:

var button = document.getElementById('myButton');
button.addEventListener('click', function(e) { 
  button.className = 'selected';
});

CSS : CSS :

.selected
{
  background-color: red;
}

你可以用这样的 javascript 来做到这一点:

document.getElementById("elementId").style.backgroundColor = "blue";

If you are using Chrome as your web browser,you can open your console and copy the code below:如果您使用 Chrome 作为网络浏览器,则可以打开控制台并复制以下代码:

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

Then you can see the background color of the question Nav changed.然后你可以看到问题 Nav 的背景颜色发生了变化。 在此处输入图片说明

在此处输入图片说明

Try This answer试试这个答案

 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