Home  >  Article  >  Web Front-end  >  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
Linda HamiltonOriginal
2024-10-20 11:47:02906browse

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>

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>

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>

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!

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