开发者

CSS-sprite menu and jQuery addClass() method

开发者 https://www.devze.com 2023-04-08 21:29 出处:网络
I\'ve created CSS sprite menu based on this tutorial: http://buildinternet.com/2010/01/how-to-make-a-css-sprite-powered-menu/

I've created CSS sprite menu based on this tutorial: http://buildinternet.com/2010/01/how-to-make-a-css-sprite-powered-menu/ Now I'd like to assign .selected class to the 'a' which was clicked as last one. I've added sipmle script:

<script>
    $("a").click(function(){
        $(this).addClass("selected");
    });
</script>

but the class .selected appears only during loading the page. After loading whole page menu item returns to its normal state. Coul开发者_Python百科d you help me with this issue? TIA

Have a nice day:)


Clicking a will take you to a different page, so this event is not gonna work for you. To add selected class to the current link you have to code like below:

<script>
 $(function(){ //short form of $(document).ready(function(){
    $("a").each(function(){

       path=window.location;
       path=String(path).split('/')['3']; //if you use absolute URLs then disable this line

       if($(this).attr('href')==path)
       {
          $(this).addClass("selected");
       }
    });
 });
</script>

It will add class selected to link(s) if it's href matches the current URL of the browser.


I believe you are making this more complicated than it needs to be. Here's a quick solution using CSS instead of bulky JS :)

First off, your body tags should have classes assigned to them.

<body class="products">

for example.

Now, in your menu, assign each <li> (I'm guessing/hoping you are using a list, you didn't supply any code so I don't know...) with classes as well.

<li class="products"><a href="/products/">Products</a></li>

for example.

Now, in your CSS, simply do this:

body.products ul#menu li.products a { /* Define how the "selected" button should look, here. */ }

These CSS rules will then only be "used" when the visitor is on the "selected" page.

This technique is the msot used as it is without a doubt the quickest and very SEO friendly as the code in your main navigation always stays the same across the site.

0

精彩评论

暂无评论...
验证码 换一张
取 消