滚动特定部分时切换类。

时间:2015-08-10 21:40:13

标签: jquery scrolltop toggleclass

我确定此问题可能之前已经被问过并回答过,但我找不到它,所以我可能没有找到正确的条款。我有一个固定的导航,当点击时,使用data-scrollto元素和类向上或向下滚动页面到页面的特定部分。我想切换一个" active"特定导航元素到达其特定部分时的类。我可以根据用户的点击来切换课程,但如果用户在页面上下滚动,我希望课程在他们滚动部分时切换。理想情况下,恰好当该部分的顶部与固定菜单的底部相遇时。

我已经嘲笑了一个codepen来尝试澄清http://codepen.io/jphogan/pen/aOMjzE

我使用以下代码设置容器的高度,并在单击特定部分时触发滚动。我正在使用jQuery和jQuery UI。

var fixedHeight = $(".navWrapper").outerHeight(true);
$(".navWrapper").css("height", fixedHeight + "px");
var innerMenuHeight = $(".navWrapperInner").outerHeight(true);

var anchors = $(".sectionAnchor");
var disableChange = false;
var menuHeight;

$( ".pageScroller" ).on("click", function( ) {
    disableChange=true;
    $("a.pageScroller").removeClass("active"); // remove class from all nav links
    $(this).addClass("active"); // add to active link
    $('html,body').animate({scrollTop: ($("." + $(this).data("scrollto")).offset().top)-innerMenuHeight-17},1000,"easeInOutSine"); // scroll to section 
    window.setTimeout(function(){disableChange=false;},480);
  return false;
});

1 个答案:

答案 0 :(得分:0)

尝试类似:

var document = $(document);
var sections = [...];

// when user scrolls
document.scroll(function () {
    var
        sy = document.scrollTop() // get scroll y
    ,   h  = $(window).height()
    ;

    var bottom = null;
    $(sections).each(function (section) {
        var sectionY = getSectionAbsoluteY(section); // absolute Y position of section
        if (sectionY < sy + h) // check if bottom-most visible
            bottom = section;
    });

    $(sections).each(...); // unhighlight
    if (bottom)
        $(bottom) ... // highlight
});
相关问题