Home >Web Front-end >JS Tutorial >How to Change the Color of Current Page Links Using CSS and jQuery?

How to Change the Color of Current Page Links Using CSS and jQuery?

Linda Hamilton
Linda HamiltonOriginal
2024-10-20 10:40:30245browse

How to Change the Color of Current Page Links Using CSS and jQuery?

How to Change the Link Color of the Current Page with CSS and jQuery

Styling links for the current page differently from others is a common task in web development. One way to achieve this is by using CSS and jQuery.

Using CSS

To style the links on the current page, you can use the following CSS:

<code class="css">li a {
  color: #A60500;
}

li a:hover {
  color: #640200;
  background-color: #000000;
}</code>

This code will change the color of all links on the page to #A60500. When a link is hovered over, its color will change to #640200, and its background color will change to #000000.

Using jQuery

You can also use jQuery to change the link color of the current page. To do this, you can use the following code:

<code class="javascript">$(document).ready(function() {
    $("[href]").each(function() {
        if (this.href == window.location.href) {
            $(this).addClass("active");
        }
    });
});</code>

This code will loop through all links on the page and add the "active" class to the link that matches the current page's URL. You can then use CSS to style the "active" class differently, such as changing its color.

Note: The jQuery code may need to be modified depending on the structure of your page and the links being used. You may need to narrow down the selection of links or strip out URL parameters to ensure the correct link is styled.

The above is the detailed content of How to Change the Color of Current Page Links Using CSS and jQuery?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn