【问题标题】:How to add a CSS class depending on URL path?如何根据 URL 路径添加 CSS 类?
【发布时间】:2013-10-14 07:43:35
【问题描述】:

如何根据我所处的路径向 div 添加 CSS 类,包括如果我在其中包含 # 则它不应该出现?

<div class="popup">
    <ul>
        <li><a href="#vs">Example 1</a></li>
        <li><a href="#bod">Example 2</a></li>
        <li><a href="#ptf">Example 3</a></li>
    </ul>
</div><!-- popup -->

<!-- how would I add the class addMe with javascript depending on the site path? It has to work with # -->

jsfiddle.net/zatox50/wBxkj/

示例 index.html

【问题讨论】:

  • 给出一些 URL 的例子并告诉你获取类名的标准。
  • 这是你的意思吗? $($(this).attr('href')).addClass('addMe');使用 jquery)。
  • @Mr_Green 看起来像我需要的东西,你能叉出我的小提琴并在那里展示它的使用吗?

标签: javascript css class


【解决方案1】:
jQuery(function($){
   switch(window.location.hash){
      case "vs":  $(".popup").addClass("class1"); break;
      case "bod":  $(".popup").addClass("class2"); break;
      case "ptf":  $(".popup").addClass("class3"); break;
   }
});

【讨论】:

  • 我无法让它工作,如果我不使用anker,在“案例”之后应该站在什么位置?例如,如果我使用 /index.html.
  • 然后使用switch(window.location.href)
  • 我不能让它工作,我用这个。 jQuery(function($){ switch(window.location.href){ case "index.html": $(".popup.").addClass("addMe"); break; } });
【解决方案2】:

这些都不适合我。这行得通:

<script type="text/javascript">
    jQuery(document).ready(function($){
        // Get current url
        // Select an a element that has the matching href and apply a class of 'active'.     Also prepend a - to the content of the link
        var url = window.location.href;
        $('.menu a[href="'+url+'"]').addClass('active');
    });
</script>

菜单结构:

<div class="menu">
    <a href="#" class="menu-element">001</a>
    <a href="#" class="menu-element">002</a>
</div> 

来源:http://www.paulund.co.uk/use-jquery-to-highlight-active-menu-item

【讨论】:

    【解决方案3】:

    这是使用 JavaScript 和 JQuery 为网站创建动态活动菜单的简单代码。

    <style>
    .myactive{
         background-color:#F7A751;
        }
        </style>
    
    <script type="text/javascript">
    $(function () {
    var url = window.location.pathname; 
    var activePage = url.substring(url.lastIndexOf('/') + 1);
        activePage === '' ?  $('#home').addClass("myactive") : $('#home').removeClass("myactive") ; // for active index page
        activePage === 'about-us' ? $('#about').addClass("myactive") : $('#about').removeClass("myactive") ; //active about us 
        activePage === 'who-we-are' ? $('#info').addClass("myactive") : 
        $('#info').removeClass("myactive") ; 
    });
    </script>  
    
    #HTML Part....
     <li id="home"><a href="#">Home</a></li>
     <li id="about"><a href="#">About</a></li>
    

    【讨论】:

      猜你喜欢
      • 2016-12-31
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 2019-10-18
      • 2019-12-28
      • 2010-11-30
      • 2017-12-17
      • 1970-01-01
      相关资源
      最近更新 更多