Добавить window.location в класс body

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

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

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

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


person Danny    schedule 17.11.2016    source источник
comment
Вы можете использовать window.location.hash для получения хэша URL. Но почему хэш меняется при прокрутке, что-то делает? Затем вы можете добавить прослушиватель для события hashchange.\   -  person Barmar    schedule 17.11.2016


Ответы (2)


Предполагая, что у вас есть какой-то механизм/виджет, который изменяет 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");
});
person vijayP    schedule 17.11.2016
comment
поэтому, когда я добавляю это, я получаю в своей консоли $(...).hashchange не является функцией.... Я обернул свой document.ready(); - person Danny; 17.11.2016
comment
о.. Я пропустил это. не могли бы вы проверить сейчас с обновленным кодом? - person vijayP; 17.11.2016
comment
Кажется, ошибка в этой строке: $(window).hashchange(); $(...).hashchange не является функцией... спасибо за вашу помощь, очень ценю ее - person Danny; 17.11.2016
comment
@ Дэнни, не могли бы вы заменить эту строку на $(window).on('hashchange', function() { - person vijayP; 17.11.2016
comment
или лучший способ; замените свой код обновленным кодом, который я только что изменил. - person vijayP; 17.11.2016
comment
Ок перестал выдавать ошибку, но в тело ничего не добавляется. pastie.org/10964075 | используя это кстати: foundation.zurb.com/sites/docs/magellan.html - person Danny; 17.11.2016

Пошел по этому поводу другим методом, хотел опубликовать его здесь для справки:

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


});
person Danny    schedule 18.11.2016