"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Change the Color of the Current Page Link with CSS and jQuery?

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

Published on 2024-11-03
Browse:356

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

Changing the Color of the Current Page Link with CSS

Manipulating the appearance of the current page link is a common CSS styling requirement. To distinguish it from other page links, users often prefer to swap the colors of the text and background. Here's a comprehensive solution for your styling request:

CSS Styling

To style the current page link, add the following CSS rules to your stylesheet:

li a {
  color: #A60500;
}

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

jQuery Script

The provided jQuery script allows you to identify the current page link and dynamically add a class to it:

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

Depending on your specific page structure, you may need to refine the selector for links ($("[href]")). For example, if the links are contained within a nav element, you can narrow down the selection to $("nav [href]").

If your page uses URL parameters, you can remove them before comparing the links to ensure that the current page link is recognized:

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

This approach eliminates the need to modify the CSS styling for each page individually.

Release Statement This article is reprinted at: 1729387336 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3