将window.location添加到正文类

问题描述:

我正在尝试放置一个平滑的滚动导航,当您滚动包含菜单的整个标题时,会更改背景颜色以匹配该节的已定义颜色。我正在为我的导航使用基金会6和magellan功能。将window.location添加到正文类

我想让我的JS获取当前的URL,并添加一个类到当前URL的正文。

var current_location = window.location.href.split('/'); 
var page = current_location[current_location.length - 1]; 

这让我我的URL散列(即:#第2节,#SECTION3)。我需要注意,因为它在页面的滚动上发生变化,并将它们添加到主体类中,同时在离开该部分之后删除前一个。

+0

您可以使用'window.location.hash'来获取URL散列。但是为什么当你滚动的时候哈希会改变,有没有这样做?然后你可以为'hashchange'事件添加一个监听器。\ – Barmar

走遍一个不同的方法,想后它在这里仅供参考:

$(document).scroll(function() { 

    var headerHeight = $('#header').height() + $('.bottom-header').height() - 4; 

    var x = $(this).scrollTop(), 
     section1 = $('#section1'), 
     section2 = $('#section2'), 
     section3 = $('#section3'), 
     section4 = $('#section4'); 
     section5 = $('#section51-a'); 


    if (x >= section1.offset().top && x < (section1.offset().top + section1.height())) { 
     $('.top-header').css("background-color", "#cc00cc"); 
    } 


    if (x >= (section2.offset().top - headerHeight) && x < (section2.offset().top + section2.height())) { 
     $('.top-header').css("background-color", "#009999"); 
    } 
    if (x >= (section3.offset().top - headerHeight) && x < (section3.offset().top + section3.height())) { 

     $('.top-header').css("background-color", "#ea148c"); 
    } 
    if (x >= (section4.offset().top - headerHeight) && x < (section4.offset().top + section4.height())) { 
     $('.top-header').css("background-color", "#999900"); 
    } 
    if (x >= (section5.offset().top - headerHeight) && x < (section5.offset().top + section5.height())) { 
     $('.top-header').css("background-color", "#0066cc"); 
    } 


}); 

假设你有某种机制/插件,其改变,只要你滚动页面,并通过@Barmar的建议你可以试试下面的代码hash

var oldHashValue = ""; //defining the global variable to store old hash value class 

$(function() { 
    // Bind an event to window.onhashchange that, when the hash changes, gets the 
    // hash and adds it as a class to <body> tag. 

    $(window).on('hashchange', function() { 
    var hash = location.hash; 

    //remove the previously added class from <body> only if its not a blank string 
    if($.trim(oldHashValue).length > 0) 
    { 
     $("body").removeClass(oldHashValue); 
    } 

    oldHashValue = hash.replace(/^#/, ""); //set the variable value 
    if($.trim(oldHashValue).length > 0) 
    { 
     //add the class to body element 
     $("body").addClass(oldHashValue); 
    } 
    }); 
    // Since the event is only triggered when the hash changes, we need to trigger 
    // the event now, to handle the hash the page may have loaded with. 
    $(window).trigger("hashchange"); 
}); 
+0

所以当我添加这个时,我会在我的控制台中获得“$(...).hashchange不是一个函数”....我已经用这个包裹了我的文档。准备(); – Danny

+0

哦..我错过了那一个。你能否请现在检查更新的代码? – vijayP

+0

似乎错误在这一行上:$(window).hashchange(); “$(...)。hashchange不是一个函数”...谢谢你的帮助,真的很感激它 – Danny