Add window.location to body class

I am trying to put together a smooth scrolling nav that as you are scrolling the entire header encompassing the menu changes background colors to match the defined color of that section. I am using Foundation 6 with the magellan feature for my nav.

I am trying to get my JS to get the current URL and add a class to the body that is the current URL.

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

This gets me my URL hash (ie: #section2, #section3). I need to watch that as it changes on scroll of the page and add those to the body class while removing the previous one after you leave that section.


假设你有一些机制/小部件,无论你何时滚动你的页面,都会改变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");
});

想了解一下这个方法,想把它发布在这里以供参考:

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


});
链接地址: http://www.djcxy.com/p/83666.html

上一篇: 从右向右滑动?

下一篇: 将window.location添加到正文类