将window.location添加到body类

时间:2016-11-17 03:41:50

标签: jquery smooth-scrolling window.location

我正在尝试组合一个平滑的滚动导航,当您滚动整个标题时,包含菜单会更改背景颜色以匹配该部分的定义颜色。我正在使用带有magellan功能的Foundation 6进行导航。

我试图让我的JS获取当前的URL并将一个类添加到当前URL的主体。

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

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

2 个答案:

答案 0 :(得分: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");
});

答案 1 :(得分: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");
    }


});