默认链接颜色保持活动状态,直到鼠标单击另一个链接

时间:2013-01-18 18:45:46

标签: jquery html css

当您进入网站时,我的默认链接颜色处于活动状态,但是当鼠标点击另一个链接并且新的当前页面现在处于活动状态时,我似乎无法将其删除。这是我的代码。

JS

$("a").on("click", function() { 
    $(".active").removeClass("active"); 
});

CSS

.active{ 
    color: #ffff00 
    !important; 
}

a { 
    text-decoration: none; 
    z-index: 5; 
    font-family: arial, "Trebuchet MS"; 
    cursor: pointer; 
    color: #2777A3; 
}

HTML

<a href="http://www.pro.com/" target="_self" class="active">Home</a>`

home page active by default but when clicked on another link, new link does not show active color

4 个答案:

答案 0 :(得分:2)

这就是你想要的吗?

$('a').click(function(){
    if ( $(this).hasClass('active') ) {
        $(this).removeClass('active')
    } else {
        $(this).addClass('active')
    }

})

答案 1 :(得分:2)

$("a").click(function() {
    $(".active").removeClass("active");
    $(this).addClass("active");
});

http://jsfiddle.net/UbVVH/1/

答案 2 :(得分:1)

如果你只有HTML,CSS和JQuery,你只需要在每个页面的右侧链接上设置active类。您不需要使用JQuery删除类。

似乎正在发生的事情是,当用户点击链接时,页面会重新加载,这会重置CSS并再次将active类放在Home链接上。每次用户点击时,页面都会刷新并重置该类。

因此,JQuery将有效地删除该类,但是点击该链接会将浏览器发送到新页面并重置CSS。

示例:

主页

<a href="http://www.pro.com/" target="_self" class="active">Home</a>
<a href="http://www.pro.com/products" target="_self">Products</a>
<a href="http://www.pro.com/solutions" target="_self">Solutions</a>

其他Page 1

<a href="http://www.pro.com/" target="_self">Home</a>
<a href="http://www.pro.com/products" target="_self" class="active">Products</a>
<a href="http://www.pro.com/solutions" target="_self">Solutions</a>

其他Page 2

<a href="http://www.pro.com/" target="_self">Home</a>
<a href="http://www.pro.com/products" target="_self">Products</a>
<a href="http://www.pro.com/solutions" target="_self" class="active">Solutions</a>

答案 3 :(得分:0)

好吧,如果你点击一个链接,我猜它会打开一个新页面,所以活动链接会在每个页面加载时重置。所以你想要做的就是检查你是否在每个链接的当前页面上。

所以也许在php:

<a href="http://www.pro.com/" target="_self" class="<?php echo ($page === 'home' ?  'active' : ''; ?>">Home</a>

如果你想做纯JavaScript:

$(document).ready(function()
{
    var path = window.location.pathname.toString().split('/')[0];

    $("a.active").removeClass("active");
    $("a." + path).addClass("active");

});

根据路径确保您的链接具有要映射的名称:

<a href="http://www.pro.com/" target="_self" class="home">Home</a>`
相关问题