Home >Web Front-end >CSS Tutorial >How Can I Style Current Page Links Differently Using CSS and JavaScript?

How Can I Style Current Page Links Differently Using CSS and JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-13 15:49:11858browse

How Can I Style Current Page Links Differently Using CSS and JavaScript?

Highlight Current Page Links with CSS

Question:

How can I alter the styling of links on the current page to distinguish them from others? Specifically, I want to swap the text and background colors.

CSS Solution:

li a {
  color: #A60500;
}

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

Example:

<ul>

JavaScript Solution:

To automatically apply the active styling, you can use jQuery's .each function:

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

Considerations:

<ul>
  • For more precise link selection, consider using a class attribute like "nav [href]".
  • If your URLs include query parameters, consider stripping them using:
  • if (this.href.split("?")[0] == window.location.href.split("?")[0]) ...

    This approach eliminates the need to manually modify each page and ensures consistent styling across different page URLs.

    The above is the detailed content of How Can I Style Current Page Links Differently Using CSS and JavaScript?. 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