2016-11-17 22 views
3

我正在嘗試放置一個平滑的滾動導航,當您滾動包含菜單的整個標題時,會更改背景顏色以匹配該節的已定義顏色。我正在爲我的導航使用基金會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

回答

0

走遍一個不同的方法,想後它在這裏僅供參考:

$(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"); 
    } 


}); 
0

假設你有某種機制/插件,其改變,只要你滾動頁面,並通過@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