How to load nav menu from an external file? (No Wamp, all code must be 'browser-side')

前端 未结 5 890
攒了一身酷
攒了一身酷 2020-12-12 07:22

I have a static HTML web site. I want to store the the nav (top) menu in an external file so when I change the menu, I want to see the change in all pages.
I RE

5条回答
  •  一向
    一向 (楼主)
    2020-12-12 07:54

    menu.html

    
    

    index.html

    
    
    
    

    js file:

    $(function() {
    
        $("#nav").load("menu.html");
    
        function activeNav() {
            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");
             });
        }
    
        setTimeout(function() {
            activeNav();
        }, 100);
    
    });
    

    The setTimeout lets the page load and then runs the function to see what link is active and then you can add a class in the css:

    #nav ul li a.active {
            color: #ff0000;
            font-weight: bold;
        }
    

提交回复
热议问题