【问题标题】:Toggle Class when scrolling over specific section.滚动特定部分时切换类。
【发布时间】:2017-10-04 16:22:57
【问题描述】:

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

我已经模拟了一个代码笔来尝试澄清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;
});

【问题讨论】:

  • 您似乎想做一些与fullpage.js 非常相似的事情。如果您将选项autoScrolling:false 用作in this example,那么您就有了想要实现的目标。 (加上几十个更多的功能)

标签: jquery scrolltop toggleclass


【解决方案1】:

尝试类似:

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
});

【讨论】:

    猜你喜欢
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多