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
Release: 2024-12-13 15:49:11
Original
871 people have browsed it

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;
}
Copy after login

Example:

<ul>
Copy after login

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");
        }
    });
});
Copy after login

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]) ...
    Copy after login

    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!

    source:php.cn
    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