【问题标题】:apply active css class to current url将活动 css 类应用于当前 url
【发布时间】:2015-09-12 11:09:36
【问题描述】:

在我使用 php 的 web 基础项目中,当用户单击导航菜单栏时,我想将 css 类 (.active) 应用于当前 url 路径,即 我的导航菜单

<li><a href="http://localhost:8000/OhdyDaran')">Designation</a></li>
<li><a href="http://localhost:8000/gallery">Gallery</a></li>
<li><a href="http://localhost:8000/Introduction">introduction</a></li>
<li><a href="http://localhost:8000/home">Home</a></li>

如何用Jquery或JS应用.active css类,页面刷新后,链接是css应用?

【问题讨论】:

    标签: javascript jquery css


    【解决方案1】:

    试试这个。

    $(document).ready(function () {
       var link = window.location.href.split('/');
       var page = link[link.length - 1];
       var url = link[link.length - 2];
    
       // now select the link based on the address
       $('li > a[href="'url + '/' + page + '"]').closest('li').addClass('active');
                })
    

    【讨论】:

    • 感谢回复,它工作正常,这里的另一个问题,页面刷新后活动类消失?如何解决它
    • @saeedahmed 在页面刷新后它工作得很好。
    • 我再次检查它,当我单击应用锚标记类时。响应后页面转到服务器端它又消失了
    • $(function(){ $('.nav a').filter(function(){ return this.href==location.href}).parent().addClass('active' ).siblings().removeClass('active') $('.nav a').click(function() { $(this).parent().addClass('active').siblings().removeClass('活动') }) });
    • 感谢我在此处粘贴的上述代码运行良好 :)
    【解决方案2】:

    可以通过这种方式获取url或者路径:

    var pathname = window.location.pathname; // Returns path only
    var url      = window.location.href;     // Returns full URL
    

    然后,如果 url 或路径与链接相同,则为其指定 .active 类。

    【讨论】:

    • 请写完整的代码,有什么困惑你想说什么?
    【解决方案3】:
    <li class="ohdyDaran">
        <a href="http://localhost:8000/ohdyDaran')">Designation</a>
    </li>
    <li class="gallery">
        <a href="http://localhost:8000/gallery">Gallery</a>
    </li>
    <li class="introduction">
        <a href="http://localhost:8000/introduction">introduction</a>
    </li>
    <li class="home">
        <a href="http://localhost:8000/home">Home</a>
    </li>
    
    <script>
    var url = window.location.href;
        var last = url.split('/');
        var clas= last[last.length-1];
        var nav = document.getElementsByClassName(clas)[0];
        nav.className = "active";
    </script>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-03
      • 1970-01-01
      相关资源
      最近更新 更多