Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
206 views
in Technique[技术] by (71.8m points)

html - How to implement changing a menu's color after it has been selected or focused on

li a:hover {
  background-color: #111;
  text-transform: lowercase;
}

li a:focus {
  background-color: green;
}
<ul>
  <li> <a tabindex=0 href="home.html"> Home</a></li>
  <li> <a tabindex=0 href="about.html"> About us</a></li>
  <li> <a tabindex=0 href="contact.html"> Contact us</a></li>
  <li> <a tabindex=0 href="products.html">Products</a></li>
  <li> <a tabindex=0 href="services.html"> Services</a></li>
</ul>
question from:https://stackoverflow.com/questions/65951081/how-to-implement-changing-a-menus-color-after-it-has-been-selected-or-focused-o

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use JavaScript to add a class active to you element. Here is an example with jQuery but you can do it with pure JavaScript.

var $link_menu = $('ul li a');
$link_menu.on('click', function() {
  // When you click on a link on your menu, it removes all the active class
  $link_menu.removeClass('active');
  // Add an active class on the selected element
  $(this).addClass('active');
});
.active {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li> <a tabindex=0 href="#"> Home</a></li>
  <li> <a tabindex=0 href="#"> About us</a></li>
  <li> <a tabindex=0 href="#"> Contact us</a></li>
  <li> <a tabindex=0 href="#">Products</a></li>
  <li> <a tabindex=0 href="#"> Services</a></li>
</ul>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...