-->

Adding active states to hyperlinks when clicked

2019-09-07 05:52发布

问题:

I am having some trouble in trying to add an active state to my links. This the code I am playing with:

$(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'));
    });
});

For some reason it won't apply the css active state class ('PnavCurrent') for the links but it does work correctly when I specify it in the script code with {$(this).css...}. Now what I would like is at add an hover state z-index for the links in the script code, something like this:

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

I've tried to use that little block of code above in trying to achieve this but it doesn't work. I would greatly appreciate it if anyone could help with this and possibly a better solution overall.

回答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');
    });
});

Note on jQuery .hover(): You dont need this here at all, but the usage would be this (this is an alternative to the css :hover rule, not used together)

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