检测滚动当前是否显示部分

时间:2015-11-14 23:02:36

标签: javascript jquery

我正在尝试根据当前部分进行某种导航。

我的代码如下:

$(function() {
    'use strict';

    function setTitle(title) {
        $('.overlay').text(title);
    }

    function removeTitle() {
        $('.overlay').text('');
    }

    $(window).on('scroll', function() {
        let windowScroll = $(window).scrollTop(),
            sections = $('section[data-title]');

        sections.each(function() {
            let thisStart = $(this).offset().top,
                thisHeight = $(this).outerHeight(true),
                thisTitle = $(this).attr('data-title'),
                thisEnd = thisHeight + thisStart;

            console.log(`start: ${thisStart}, end: ${thisEnd}, scroll: ${windowScroll}`);

            if(windowScroll >= thisStart && windowScroll < thisEnd) {
                setTitle(thisTitle);
            } else {
                removeTitle();
            }
        });
    });
});

HTML

<section class="section section-first"></section>
<section class="section section-what" data-title="First">
</section>
<section class="section section-cv" data-title="Secound">
</section>
<div class="overlay"></div>

不幸的是,它仅适用于最后.section。我该怎么办?

请参阅我的CodePen,了解我的意思:http://codepen.io/tomekbuszewski/pen/Xmovwq

1 个答案:

答案 0 :(得分:1)

在此处添加return false;

if(windowScroll >= thisStart && windowScroll < thisEnd) {
    setTitle(thisTitle);
    return false;        // <- add this
} else {
    removeTitle();
}

这将突破each方法并阻止标题一旦被设置就被删除。

CodePen