2016-11-17 8 views
3

Я пытаюсь создать гладкую навигацию прокрутки, поскольку при прокрутке всего заголовка, охватывающего меню, меняются цвета фона в соответствии с определенным цветом этого раздела. Я использую Foundation 6 с функцией magellan для моего навигатора.Добавить window.location в класс body

Я пытаюсь заставить мой JS получить текущий URL-адрес и добавить класс к телу, который является текущим URL-адресом.

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

Это получает мой URL-адрес хеша (т. Е .: # section2, # section3). Мне нужно посмотреть, как это изменится при прокрутке страницы и добавьте их в класс body, удалив предыдущий после того, как вы покинете этот раздел.

+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

Если предположить, что у вас есть некоторый механизм/виджет, который изменяет hash всякий раз, когда вы прокрутите страницу И как предложено @Barmar вы можете попробовать следующий код:

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