Home > Web Front-end > JS Tutorial > 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?

Linda Hamilton
Release: 2024-10-20 11:47:02
Original
1038 people have browsed it

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:

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

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

jQuery Script

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

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

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:

<code class="javascript">if (this.href.split("?")[0] == window.location.href.split("?")[0]) ...</code>
Copy after login

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

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

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template