将样式应用于活动超链接,而不为每个超链接指定类



我希望用户通过突出显示超链接来了解他们当前所在的页面。

如果重要的话,我不会使用按钮列表(<li>),我只是使用链接。

我不想在每个页面上给每个链接一个类来判断它是否处于活动状态。

有没有在不给每个活动链接一个类的情况下这样做?

我已经研究过这个问题,从我的角度来看,jQuery可能是一种可能性,但我更喜欢使用它,因为我对jQuery一无所知。如果有人知道任何jQuery解决方案,我很乐意看看!

有关于的自动活动链接检测器吗?:)

我认为这可能有效,但我还没有测试过。
它使用的是jQuery,可读性很强。
但是,您应该处理路径名称,使其仅具有hrefHasPath函数中匹配所需的部分。

var links = $("#links a");               // gets all links within something with an id of "links"
var pathname = window.location.pathname; // current url
//for each link see if the href has something in the path, and if it does add a css class
$.each(links, function(){ 
    if(hrefHasPath($(this).attr("href"))){
        $(this).addClass("highlight");
    } 
});
function hrefHasPath(href){
    return (href.indexOf("pathname ") != -1);
}

在我的脑海中,我会通过抓取所有<a>元素(或某个分组中或类中的元素,如导航)并检查CURRENT URL==a.href

类似的东西:

var a = document.getElementsByTagName('a');
for (var idx= 0; idx < a.length; ++idx){
    if(a[idx].href == document.URL){
        // some styles here to the link background
        a[idx].style.backgroundColor = 'red';  
    }
}

如果您添加jQuery,它将使选择器更容易进行样式设置等操作。

最新更新