gpt4 book ai didi

javascript - 检测部分当前在滚动上是否可见

转载 作者:行者123 更新时间:2023-11-27 23:40:30 27 4
gpt4 key购买 nike

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

我的代码如下:

$(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

最佳答案

在此处添加return false;:

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

这将突破 each 方法并防止标题设置后被删除。

CodePen

关于javascript - 检测部分当前在滚动上是否可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33714407/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com