Home > Web Front-end > JS Tutorial > body text

How to Dynamically Change the Color of Links for the Current Page?

DDD
Release: 2024-10-20 09:39:02
Original
687 people have browsed it

How to Dynamically Change the Color of Links for the Current Page?

Changing the Color of Links for the Current Page

Modifying the appearance of links for the page currently being viewed can enhance user experience by providing visual cues. One common technique is to swap the colors of the text and background to make the current link stand out.

To achieve this effect, CSS and JavaScript can be employed. CSS defines the desired appearance of the links, while JavaScript dynamically identifies the current page and applies the styling accordingly.

Here's how to implement this solution:

  1. CSS Styling:

    • Define the base styling for all links:

      <code class="css">li a {
      color: #A60500;
      }</code>
      Copy after login
    • Specify the styling for active links:

      <code class="css">li a:hover {
      color: #640200;
      background-color: #000000;
      }</code>
      Copy after login
  2. JavaScript:

    • Use the .each function to iterate through the links:

      <code class="javascript">$(document).ready(function() {
        $("[href]").each(function() {
            if (this.href == window.location.href) {
                $(this).addClass("active");
            }
        });
      });</code>
      Copy after login
    • Optionally, narrow down the link selection:

      <code class="javascript">$("nav [href]").each ...</code>
      Copy after login
    • Handle URL parameters if necessary:

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

By implementing this solution, the current page link will be visually distinct from others, providing a clear indication to users.

The above is the detailed content of How to Dynamically Change the Color of Links for the Current Page?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!