改变<a> tag for JavaScript</a>

时间:2013-05-02 17:07:53

标签: javascript jquery

我如何利用JavaScript将活动链接状态移动到另一个链接?

请参阅codepen:

http://codepen.io/Krish1980/pen/mGfed

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script type="text/javascript">

$(function(){
$('#nav a').on('click',function(){
$('#nav li').removeClass('active');
$(this).parent().addClass('active');
   });
});
</script>

1 个答案:

答案 0 :(得分:0)

//Wrap the click handler in DocumentReady so that the handler is 
//attached only after the elements have been loaded into the DOM
$(document).ready(function() {

    //Attach the click handler to all <li> elements that are under
    //the element with ID "nav"
    $("#nav li").click(function() {

        //Whenever one of the <li> elements is clicked, remove the
        //"active" class from any element that currently has it.
        $(".active").removeClass("active");

        //Add the "active" class to the element that triggered this function
        //(the <li> that was clicked)
        $(this).addClass("active");

    });

});

如果您将此代码复制并粘贴到.html文件中并使用浏览器打开它,您将看到它按照您希望的方式运行:

<html>
<head>
<style>
body{background:#f9d867; margin:0; padding:0;}
#nav{display:block; background:#f5f5f5;  
-moz-box-shadow: 0 0 4px 0px #999;
-webkit-box-shadow: 0 0 4px 0px #999;
box-shadow: 0 0 4px 0px #999; margin:0; padding:40px 20px; list-style:none; text-align:center; }
#nav li{display:inline-block;}
#nav li a{display:block; padding:10px 15px; font:1em "Arial Black", Gadget, sans-serif; color:#444; text-decoration:none; text-transform:uppercase;}
#nav li a:hover{color:#999;}
#nav li.active a{background:#fff; 
-moz-box-shadow: 5px 5px 0px 0px rgba(0, 0, 0, 0.1);
-webkit-box-shadow: 5px 5px 0px 0px rgba(0, 0, 0, 0.1);
box-shadow: 5px 5px 0px 0px rgba(0, 0, 0, 0.1);}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
   $("#nav li").click(function() {
      $(".active").removeClass("active");
      $(this).addClass("active");
   });
});
</script>
</head>
<body>
   <ul id="nav">
      <li>
         <a href="#">art</a>
      </li>
      <li>
         <a href="#">archive</a>
      </li>
      <li>
         <a href="#">about</a>
      </li>
      <li>
         <a href="#">blog</a>
      </li>
      <li class="active">
         <a href="#">contact</a>
      </li>
   </ul>
</body>
</html>