添加 window.location 到 body class

Add window.location to body class

我正在尝试将一个平滑的滚动导航放在一起,当您滚动整个 header 包含菜单时,它会更改背景颜色以匹配该部分的定义颜色。我正在使用具有 magellan 功能的 Foundation 6 导航。

我正在尝试让我的 JS 获取当前 URL 并将 class 添加到 body 即当前 URL.

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

这得到了我的 URL 哈希值(即:#section2、#section3)。我需要观察它在滚动页面时发生的变化,并将它们添加到 body class,同时在离开该部分后删除前一个。

假设你有一些 mechanism/widget 当你滚动你的页面时它会改变 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");
});

换了个方法,想post这里参考一下:

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


});