【问题标题】:Dynamically change CSS of link based on current page根据当前页面动态改变链接的 CSS
【发布时间】:2012-03-26 04:02:05
【问题描述】:

我的网页顶部有以下链接:

 <ul class="icyLink">

      <li><a class="nav1" href="index.html">The World of Icengale</a></li>
      <li><a class="nav1" href="history.htm">History of Icengale</a></li>
      <li><a class="nav1" href="calendar.htm">Time & Calendar of Icengale</a></li>

 </ul>

每个链接的颜色为蓝色,每个&lt;li&gt; 都有一个背景图片(background-image: url('../images/blue2.jpg')。

我想做的是根据当前页面动态更改单个链接的 css。例如,如果有人在 history.htm 页面上,则链接的颜色将变为白色,而背景图像将变为另一个(在本例中为“blue3”)。所有其他链接的 css 将保持为一样。我该怎么做?

一如既往,非常感谢任何和所有帮助!

保重,祝你有美好的一天......

乔, 约翰。

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    您可以检查每个链接,看看它是否与当前位置匹配。根据您的需要,这可能或多或少是高级的,但类似于:

    var loc = window.location.pathname;
    
    $('.icyLink').find('a').each(function() {
      $(this).toggleClass('active', $(this).attr('href') == loc);
    });
    

    然后在 CSS 中设置活动类的样式:

    .icyLink a.active{color:#fff}
    

    【讨论】:

      【解决方案2】:

      您正在寻找 jQuery .css.addClass 函数。

      【讨论】:

        【解决方案3】:

        在每个页面中设置一个唯一的body id,然后在每个菜单项上设置一个id:

        #home-page #home-menu,
        #history-page #history-menu { background: blue; } // Etc....
        

        【讨论】:

          【解决方案4】:
          <ul class="icyLink">
          
            <li><a class="nav1" href="index.html">The World of Icengale</a></li>
            <li><a class="nav1" href="history.htm">History of Icengale</a></li>
            <li><a class="nav1" href="calendar.htm">Time & Calendar of Icengale</a></li>
          
          </ul>
          <script>
          $(document).ready(function(){
             $("a.nav1").click(function () {
                // switch all tabs off
                $(".active").removeClass("active");
                // switch this tab on
                $(this).addClass("active");
             });
          });
          </script>
          

          css

          .active{background-image: url('../images/blue3.jpg');color:#fff;}
          

          【讨论】:

          • 这不起作用,因为一旦链接被激活,新页面就会加载,所以你会得到一个没有新标记的新页面。
          猜你喜欢
          • 2021-12-07
          • 2016-10-25
          • 1970-01-01
          • 2011-01-24
          • 1970-01-01
          • 1970-01-01
          • 2010-09-15
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多