Javascript 使用 CSS 更改当前页面的链接颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2397370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:06:46  来源:igfitidea点击:

Change link color of the current page with CSS

javascripthtmlcss

提问by Josh Curren

How does one style links for the current page differently from others? I would like to swap the colors of the text and background.

当前页面的一种样式链接与其他样式有何不同?我想交换文本和背景的颜色。

HTML:

HTML:

<ul id="navigation">
    <li class="a"><a href="/">Home</a></li>
    <li class="b"><a href="theatre.php">Theatre</a></li>
    <li class="c"><a href="programming.php">Programming</a></li> 
</ul>

CSS:

CSS:

li a{
    color:#A60500;
}

li a:hover{
    color:#640200;
    background-color:#000000;
}

回答by Taraman

With jQuery you could use the .eachfunction to iterate through the links with the following code:

使用 jQuery,您可以使用该.each函数通过以下代码迭代链接:

$(document).ready(function() {
    $("[href]").each(function() {
        if (this.href == window.location.href) {
            $(this).addClass("active");
        }
    });
});

Depending on your page structure and used links, you may have to narrow down the selection of links like:

根据您的页面结构和使用的链接,您可能需要缩小链接的选择范围,例如:

$("nav [href]").each ...

If you are using URL parameters, it may be necessary to strip these:

如果您使用 URL 参数,则可能需要去除这些参数:

if (this.href.split("?")[0] == window.location.href.split("?")[0]) ...

This way you don't have to edit each page.

这样您就不必编辑每个页面。

回答by N 1.1

a:active: when you click on the link and hold it (active!).
a:visited: when the link has already been visited.

a:active:当您点击链接并按住它时(激活!)。
a:visited: 当链接已被访问时。

If you want the link corresponding to the current page to be highlighted, you can define some specific style to the link -

如果你想让当前页面对应的链接高亮显示,你可以为链接定义一些特定的样式——

.currentLink {
   color: #640200;
   background-color: #000000;
}

Add this new class only to the corresponding li(link), either on server-side or on client-side (using JavaScript).

仅将这个新类添加到相应的li(链接),无论是在服务器端还是在客户端(使用 JavaScript)。

回答by Andy G

It is possible to achieve this without having to modify each page individually (adding a 'current' class to a specific link), but still without JS or a server-side script. This uses the :targetpseudo selector, which relies on #someidappearing in the addressbar.

无需单独修改每个页面(将“当前”类添加到特定链接)就可以实现这一点,但仍然没有 JS 或服务器端脚本。这使用了:target伪选择器,它依赖于#someid出现在地址栏中。

<!DOCTYPE>
<html>
<head>
    <title>Some Title</title>
<style>
:target {
    background-color: yellow;
}
</style>
</head>
<body>
<ul>
    <li><a id="news" href="news.html#news">News</a></li>
    <li><a id="games" href="games.html#games">Games</a></li>
    <li><a id="science" href="science.html#science">Science</a></li>
</ul>
<h1>Stuff about science</h1>
<p>lorem ipsum blah blah</p>
</body>
</html>

There are a couple of restrictions:

有几个限制:

  • If the page wasn't navigated to using one of these links it won't be coloured;
  • The ids need to occur at the top of the page otherwise the page will jump down a bit when visited.
  • 如果未使用这些链接之一导航到该页面,则该页面不会被着色;
  • id 需要出现在页面的顶部,否则页面在访问时会跳下一点。

As long as any links to these pages include the id, and the navbar is at the top, it shouldn't be a problem.

只要指向这些页面的任何链接都包含 id,并且导航栏位于顶部,就不会有问题。



Other in-page links (bookmarks) will also cause the colour to be lost.

其他页内链接(书签)也会导致颜色丢失。

回答by Govind Rai

JavaScript will get the job done.

JavaScript 将完成这项工作。

Get all links in the document and compare their reference URLs to the document's URL. If there is a match, add a class to that link.

获取文档中的所有链接并将它们的参考 URL 与文档的 URL 进行比较。如果匹配,则向该链接添加一个类。

JavaScript

JavaScript

<script>
    currentLinks = document.querySelectorAll('a[href="'+document.URL+'"]')
    currentLinks.forE??ach(function(link) {
        link.className += ' current-link')
    });
</script>

One Liner Version of Above

One Liner Version of Above

document.querySelectorAll('a[href="'+document.URL+'"]').forE??ach(function(elem){e??lem.className += ' current-link')});

CSS

CSS

.current-link {
    color:#baada7;
}

Other Notes

其他注意事项

Taraman's jQuery answer above only searches on [href]which will return linktags and tags other than awhich rely on the hrefattribute. Searching on a[href='*https://urlofcurrentpage.com*']captures only those links which meets the criteria and therefore runs faster.

上面 Taraman 的 jQuery 答案只搜索[href]哪些将返回link标签,而不是a依赖于href属性的标签。搜索a[href='*https://urlofcurrentpage.com*']仅捕获那些符合条件的链接,因此运行速度更快。

In addtion, if you don't need to rely on the jQuery library, a vanilla JavaScript solution is definitely the way to go.

此外,如果您不需要依赖 jQuery 库,那么 vanilla JavaScript 解决方案绝对是您要走的路。

回答by Alex

N 1.1's answer is correct. In addition, I've written a small JavaScript function to extract the current link from a list, which will save you the trouble of modifying each page to know its current link.

N 1.1 的答案是正确的。此外,我还编写了一个小的 JavaScript 函数来从列表中提取当前链接,这将省去您修改每个页面以了解其当前链接的麻烦。

<script type="text/javascript">

function getCurrentLinkFrom(links){

    var curPage = document.URL;
    curPage = curPage.substr(curPage.lastIndexOf("/")) ;

    links.each(function(){
        var linkPage = $(this).attr("href");
        linkPage = linkPage.substr(linkPage.lastIndexOf("/"));
        if (curPage == linkPage){
            return $(this);
        }
    });
};

$(document).ready(function(){
    var currentLink = getCurrentLinkFrom($("navbar a"));
    currentLink.addClass("current_link") ;
});
</script>

回答by rekha_sri

a:link-> It defines the style for unvisited links.

a:link-> 它定义了未访问链接的样式。

a:hover-> It defines the style for hovered links.

a:hover-> 它定义了悬停链接的样式。

A link is hovered when the mouse moves over it.

当鼠标移到链接上时,它会悬停在链接上。

回答by webestdesigns

include this! on your page where you want to change the colors save as .php

包括这个!在您想要更改颜色的页面上另存为 .php

<?php include("includes/navbar.php"); ?>

then add a new file in an includes folder.

然后在包含文件夹中添加一个新文件。

includes/navbar.php

<div <?php //Using REQUEST_URI

$currentpage = $_SERVER['REQUEST_URI'];

if(preg_match("/index/i", $currentpage)||($currentpage=="/"))
    echo " class=\"navbarorange/*the css class for your nav div*/\" ";
elseif(preg_match("/about/*or second page name*//i", $currentpage))
    echo " class=\"navbarpink\" ";
elseif(preg_match("/contact/* or edit 3rd page name*//i", $currentpage))
    echo " class=\"navbargreen\" ";?> >
</div>

回答by greg

Best and easiest solution:

最佳和最简单的解决方案:

For each page you want your respective link to change color to until switched, put an internal style in EACH PAGE for the VISITED attribute and make each an individual class in order to differentiate between links so you don't apply the feature to all accidentally. We'll use white as an example:

对于每个页面,您希望各自的链接在切换之前更改颜色,在每个页面中为 VISITED 属性放置一个内部样式,并使每个页面成为一个单独的类,以便区分链接,这样您就不会意外地将该功能应用于所有页面。我们将以白色为例:

<style type="text/css">
.link1 a:visited {color:#FFFFFF;text-decoration:none;} 
</style>

For all other attributes such as LINK, ACTIVE and HOVER, you can keep those in your style.css. You'll want to include a VISITED there as well for the color you want the link to turn back to when you click a different link.

对于所有其他属性,例如 LINK、ACTIVE 和 HOVER,您可以将它们保留在 style.css 中。您还需要在那里包含一个 VISITED 以及当您单击其他链接时希望链接返回的颜色。

回答by Salaam

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html><head>

<style type="text/css"><!--

.class1 A:link {text-decoration: none; background:#1C1C1C url(..../images/menu-bg.jpg) center top no-repeat; border-left: 4px solid #333333; border-right: 4px solid #333333; border-top: 3px solid #333333;  border-bottom: 4px solid #333333;}

.class1 A:visited {text-decoration: none; background:#1C1C1C url(..../images/menu-bg.jpg) center top no-repeat; border-left: 4px solid #333333; border-right: 4px solid #333333; border-top: 3px solid #333333;  border-bottom: 4px solid #333333;}

.class1 A:hover {text-decoration: none; background:#1C1C1C url(..../images/menu-bg.jpg) center top no-repeat; border-left: 3px solid #0000FF; border-right: 3px solid #0000FF; border-top: 2px solid #0000FF;  border-bottom: 2px solid #0000FF;}

.class1 A:active {text-decoration: none; background:#1C1C1C url(..../images/menu-bg.jpg) center top no-repeat; border-left: 3px solid #0000FF; border-right: 3px solid #0000FF; border-top: 2px solid #0000FF;  border-bottom: 2px solid #0000FF;}

#nav_menu .current {text-decoration: none; background:#1C1C1C url(..../images/menu-bg.jpg) center top no-repeat; border-left: 3px solid #FF0000; border-right: 3px solid #FF0000; border-top: 2px solid #FF0000;  border-bottom: 2px solid #FF0000;}


a:link {text-decoration:none;}

a:visited {text-decoration:none;}

a:hover {text-decoration:none;}

a:active {text-decoration:none;}

--></style>

</head>

<body style="background:#000000 url('...../images/bg.jpg') repeat-y top center fixed; width="100%" align="center">

<table style="table-layout:fixed; border:0px" width=100% height=100% border=0 cellspacing=0 cellpadding=0 align=center><tr>

<td style="background: url(...../images/menu_bg-menu.jpg) center no-repeat;" "border:0px" width="100%" height="100%" align="center" valign="middle">

<span class="class1" id="nav_menu">

<a href="http://Yourhomepage-url.com/" ***class="current"*** target="_parent"><font face="Georgia" color="#0000FF" size="2"><b>&nbsp;&nbsp;Home&nbsp;&nbsp;</b></font></a>

&nbsp;&nbsp;

<a href="http://Yourhomepage-url.com/yourfaqspage-url.php_or_.html" target="_parent"><font face="Georgia" color="#0000FF" size="2"><b>&nbsp;&nbsp;FAQs page&nbsp;&nbsp;</b></font></a>

&nbsp;&nbsp;

<a href="http://Yourhomepage-url.com/youraboutpage-url.php_or_.html" target="_parent"><font face="Georgia" color="#0000FF" size="2"><b>&nbsp;&nbsp;About&nbsp;&nbsp;</b></font></a>

&nbsp;&nbsp;

<a href="http://Yourhomepage-url.com/yourcontactpage-url.php_or_.html" target="_parent"><font face="Georgia" color="#0000FF" size="2"><b>&nbsp;&nbsp;Contact&nbsp;&nbsp;</b></font></a>
</span>

</td></tr></table></body></html>

Note: the style goes in between the head tag (<head> .... </head>) and the class="class1" and the id="nav_menu" goes in the ie: (-- <span class="class1" id="nav_menu">--).

注意:样式位于 head 标记 ( <head> .... </head>) 和 class="class1" 之间,而 id="nav_menu" 位于 ie: (- <span class="class1" id="nav_menu">--) 中。

Then the last class attribute (class="current") goes in the hyper-link code of the link in the page that you want the active current link to correspond to.

然后最后一个类属性(class="current")进入您希望当前活动链接对应的页面中链接的超链接代码。

Example: You want the link tab to stay active or highlighted when it's correspondent page is whats currently in view, go to that page itself and place the class="current"attribute by it's link's html code. Only in the page that corresponds to the link so that when ever that page is at view, the tab will stay highlighted or stand out different from the rest of the tabs.

示例:您希望链接选项卡在其对应页面当前处于查看状态时保持活动状态或突出显示,转到该页面本身并通过其链接的 html 代码放置class="current"属性。仅在与链接对应的页面中,以便在查看该页面时,该选项卡将保持突出显示或与其他选项卡不同。

For the Home page, go to the home page and place the class in it. example: <a href="http://Yourhomepage-url.com/" class="current" target="_parent">

对于主页,转到主页并将类放入其中。例子:<a href="http://Yourhomepage-url.com/" class="current" target="_parent">

For the About page, go to the about page and place the class in it. example: <a href="http://Yourhomepage-url.com/youraboutpage-url.php_or_.html" class="current" target="_parent">

对于 About 页面,转到 about 页面并将类放入其中。例子:<a href="http://Yourhomepage-url.com/youraboutpage-url.php_or_.html" class="current" target="_parent">

For the Contact page, go to the contact page and place the class in it. example: <a href="http://Yourhomepage-url.com/youraboutpage-url.php_or_.html" class="current" target="_parent">

对于联系页面,转到联系页面并将类放入其中。例子:<a href="http://Yourhomepage-url.com/youraboutpage-url.php_or_.html" class="current" target="_parent">

etc ......

等等 ......

Notice the example Table above;- Lets assume this was the Home page, so on this page, only the Home url link section has the class="current"

请注意上面的示例表;- 让我们假设这是主页,因此在此页面上,只有主页 url 链接部分具有 class="current"

Sorry for any meaning-less error, am not a prof. but this worked for me and displays fine in almost all the browsers tested, including ipad, and smart phones. Hope this will help some-one out here because is very frustrating to want to and not able to. I had tried so had to get to this, and so far it's good for me.

抱歉任何无意义的错误,我不是教授。但这对我有用,并且在几乎所有测试过的浏览器中都显示良好,包括 ipad 和智能手机。希望这会帮助这里的某个人,因为想要但无法做到非常令人沮丧。我已经尝试过,所以必须做到这一点,到目前为止,这对我有好处。

回答by Rhianna

@Presto Thanks! Yours worked perfectly for me, but I came up with a simpler version to save changing everything around.

@Presto 谢谢!你的非常适合我,但我想出了一个更简单的版本来保存改变周围的一切。

Add a <span>tag around the desired link text, specifying class within. (e.g. home tag)

<span>在所需的链接文本周围添加一个标签,指定其中的类。(例如家庭标签)

<nav id="top-menu">
    <ul>
        <li> <a href="home.html"><span class="currentLink">Home</span></a> </li>
        <li> <a href="about.html">About</a> </li>
        <li> <a href="cv.html">CV</a> </li>
        <li> <a href="photos.html">Photos</a> </li>
        <li> <a href="archive.html">Archive</a> </li>
        <li> <a href="contact.html">Contact</a></li>
    </ul>
</nav>

Then edit your CSS accordingly:

然后相应地编辑您的 CSS:

.currentLink {
    color:#baada7;
}