将window.location添加到正文类

我正在尝试放置一个平滑的滚动导航栏,当您滚动包含菜单的整个标题栏时,会更改背景颜色以匹配该节的已定义颜色。 我正在为我的导航使用基金会6和magellan功能。

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

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

这让我的网址哈希(即:#section2,#section3)。 我需要注意,因为它在页面的滚动上发生变化,并将它们添加到主体类中,同时在离开该部分之后删除前一个。


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

上一篇: Add window.location to body class

下一篇: Changing color of nav pills bootstrap