【问题标题】:Adding active states to hyperlinks when clicked单击时向超链接添加活动状态
【发布时间】:2012-07-19 05:50:08
【问题描述】:

我在尝试向我的链接添加活动状态时遇到了一些麻烦。这是我正在玩的代码:

$(function () {

    $('a').click(function () {
        $(this).addClass('PnavCurrent');
        //$("div a").removeClass("PnavCurrent");
        //$("div a[href="+newHash+"]").addClass("PnavCurrent");

        $(this).removeClass('PnavCurrent');
        $(this).css('color', '#51ad9d');
        $(this).css('z-index', '2');
        $(this).css('border-color', '#00a8ff');

        $('a').hover($(this).css('z-index', '10'));
    });
});

由于某种原因,它不会为链接应用 css 活动状态类 ('PnavCurrent'),但当我在脚本代码中使用 {$(this).css...} 指定它时,它确实可以正常工作。现在我想要的是为脚本代码中的链接添加一个悬停状态 z-index,如下所示:

 $('a').hover($(this).css ('z-index', '10'));

我尝试使用上面的那一小段代码来实现这一点,但它不起作用。如果有人能帮助解决这个问题并可能提供更好的整体解决方案,我将不胜感激。

【问题讨论】:

  • 您正在添加然后删除类PnavCurrent

标签: jquery ajax jquery-hover


【解决方案1】:

CSS:

.PnavCurrent {
    color: #51ad9d;
    z-index: 2;
    border-color: #00a8ff;
}

.PnavCurrent:hover { z-index: 10; }

Javascript:

$(function() {
    $('a').click(function(e) {
        // you usually want to prevent default for handling link clicks,
        // otherwise the browser follows the href (if that's intended skip this)
        e.preventDefault();

        $('a').not(this).removeClass('PnavCurrent');
        $(this).addClass('PnavCurrent');
    });
});

注意jQuery .hover(): 你在这里根本不需要这个,但用法是这样(这是css :hover 规则的替代,不一起使用)

$("a").hover(
    function () {
        $(this).css('z-index',2));
    }, 
    function () {
        $(this).css('z-index', 10);
    }
);

【讨论】:

  • 抱歉回复时间长。我认为我的 css 中的某些内容与此脚本冲突,因为当我从头开始测试新文件(html 和 css)时,它可以工作,尽管存在一些问题,例如它不记得我的链接在页面重新加载时的活动状态等。但总的来说有用。非常感谢nbrooks。你给了我很大的帮助,我很感激。
猜你喜欢
  • 2020-06-04
  • 2017-08-23
  • 2021-07-15
  • 2022-12-31
  • 2018-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多