CSS精灵菜单和jQuery addClass()方法 [英] CSS-sprite menu and jQuery addClass() method

查看:147
本文介绍了CSS精灵菜单和jQuery addClass()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经根据本教程创建了CSS Sprite菜单: http://buildinternet.com/2010/01/如何制作一个CSS精灵供电的菜单/ 现在,我想将.selected类分配给最后一个被单击的'a'.我添加了sipmle脚本:

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>

,但是.selected类仅在加载页面期间出现.加载整个页面后,菜单项将返回其正常状态.您能帮我解决这个问题吗? TIA

but the class .selected appears only during loading the page. After loading whole page menu item returns to its normal state. Could you help me with this issue? TIA

祝您有美好的一天:)

推荐答案

单击a会将您带到其他页面,因此此事件将不适合您.要将selected类添加到当前链接,您必须像下面这样编写代码:

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>

如果href与浏览器的当前URL匹配,它将在链接中添加类selected.

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

这篇关于CSS精灵菜单和jQuery addClass()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆