You may have encountered the effect of switching the background of the navigation bar when browsing the web. Here is an introduction to how to implement it using jquery. The specific ideas and code are as follows. Interested friends can refer to it
The effect is as follows:
Copy code The code is as follows:
<DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-2.0.3.min.js"></script> <meta charset="UTF-8"> <style> .nav{height:40px; width: 100%;background: #E6E6E6;} .nav ul li{float: left;list-style: none;margin-right: 20px;line-height: 40px;} .nav ul li a{text-decoration: none; display: block;width: 60px; text-align: center;} .onNav{font-weight: bold;color:#fff; background: #ccc;} </style> </head> <body> <p class="nav"> <ul> <li><a href="#" class="onNav">首页</a></li> <li><a href="#">博客</a></li> <li><a href="#">论坛</a></li> <li><a href="#">关于</a></li> <li><a href="#">联系</a></li> </ul> </p> <script type="text/javascript"> $(".nav ul li a").click(function(){if($(this).has(".onNav")){ $(this).addClass("onNav").parent("li").siblings("li").find("a").removeClass("onNav");}}) </script> </body> </html>
js part:
Copy code The code is as follows:
<script type="text/javascript"> $(".nav ul li a").click(function(){if($(this).has(".onNav")){ //找到a标签添加click事件,判断是否有背景存在 $(this).addClass("onNav").parent("li").siblings("li").find("a").removeClass("onNav");}}) //添加类并移除已有的类 </script>
The above is one method, the following is another method:
Copy code The code is as follows:
<script type="text/javascript"> $(".nav ul li a").click(function(){ //找到a标签并添加click事件 var inx = $(this).parent("li").index(); //定义变量inx,返回这个元素在同辈中的索引位置 $(".nav ul li").find("a").removeClass("on_nav"); //移除已有的类 $(".nav ul li").eq(inx).find("a").addClass("on_nav"); //获取点击元素并添加类 </script>
The above is the detailed content of Code sharing for jQuery to implement navigation bar background switching effect. For more information, please follow other related articles on the PHP Chinese website!