亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

基于當前 URL 問題的主動導航類

基于當前 URL 問題的主動導航類

幕布斯6054654 2021-06-15 21:48:58
我有以下 HTML 菜單:<div class="nav">            <ul>                <li class="first"><a href="/">Home</a></li>                <li><a href="/something/">Something</a></li>                <li><a href="/else/">Else</a></li>                <li class="last"><a href="/random/">Random</a></li>            </ul>            <ul style="float:right;">                   <li class="first last"><a href="/news/">News</a></li>            </ul>        </div>    </div>然后我有這個代碼:jQuery(function($){    var current = location.pathname;    $('.nav ul li a').each(function(){        var $this = $(this);        // if the current path is like this link, make it active        if($this.attr('href').indexOf(current) !== -1){            $this.addClass('active');        }    })})代碼運行良好,但有問題。例如,如果我看到主頁 (www.example.com),那么所有菜單鏈接都會收到活動類。另一個問題是它適用于 www.example.com/something 但如果我去 www.example.com/something/1 等,它不會保持活動狀態。知道如何解決這個問題嗎?提前致謝!
查看完整描述

3 回答

?
qq_花開花謝_0

TA貢獻1835條經驗 獲得超7個贊

對于主頁,在列表中添加額外的類“默認”。


<li class="first default"><a href="/">Home</a></li>

jQuery 代碼。


 jQuery(function($){

        var current = location.pathname;

        console.log(current);

        //remove the active class from list item. 

        $('.nav ul li a').removeClass('active');


        if(current != '/'){

            $('.nav ul li a').each(function(){

                var $this = $(this);

                // if the current path is like this link, make it active

                if(current.indexOf($this.attr('href')) !== -1 && $this.attr('href') != '/'){

                    $this.addClass('active');

                }

            })

        }else{

             console.log('home');

            $('.default a').addClass('active');

        }

    })


查看完整回答
反對 回復 2021-06-24
?
桃花長相依

TA貢獻1860條經驗 獲得超8個贊

使用以下 jQuery 代碼添加active類:


$(function() {

      var pgurl = window.location.href.substr(window.location.href

         .lastIndexOf("/") + 1);

      $(".nav ul li a").each(function() {

         if ($(this).attr("href") == pgurl || $(this).attr("href") == '')

            $(this).addClass("active");

      })

   });


查看完整回答
反對 回復 2021-06-24
  • 3 回答
  • 0 關注
  • 151 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號