多元素Waypoints应用:滚动更新标题向上滚动不同步问题
解决Waypoints滚动标题不同步问题
问题根源
你的代码有两个关键问题:
- 选择器错误:
$("project")应该是$(".project")(类选择器需要加.才能正确选中元素); - Waypoints默认会在元素进入和离开偏移区域时都触发回调,向上滚动时,前一个元素离开偏移位置就会触发更新,导致标题和当前显示的图片不匹配。
我们需要调整逻辑,让标题仅在视口50%位置落在对应图片范围内时显示。
修正后的代码
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/waypoints/4.0.1/jquery.waypoints.js"></script> <h1 id="header">Header one</h1> <div id="projects"> <div data-title="Header one" class="project">1</div> <div data-title="Header two" class="project">2</div> <div data-title="Header three" class="project">3</div> <div data-title="Header four" class="project">4</div> </div>
CSS
* { margin: 0; padding: 0; box-sizing: border-box; } h1 { position: fixed; left: 50%; top: 50%; transform: translate(-50%, -50%); text-align: center; } #projects { margin: 0 auto; width: 400px; padding-top: 400px; } .project { background: pink; width: 400px; height: 600px; margin-bottom: 100px; }
(注:原CSS里transform属性有重复语法错误,已简化为标准的居中写法)
JavaScript
// 为每个项目绑定Waypoint监听 $(".project").waypoint(function(direction) { const title = this.element.getAttribute("data-title"); const $header = $("#header"); // 向下滚动:元素顶部到达视口中间时,更新为当前项目标题 if (direction === "down") { $header.text(title); } // 向上滚动:当前元素底部离开视口中间时,切换到上一个项目的标题 else { const prevProject = $(this.element).prev(".project"); if (prevProject.length) { $header.text(prevProject.data("title")); } else { // 滚动到第一个项目时,显示初始标题 $header.text($(".project").first().data("title")); } } }, { offset: "50%" // 触发点为元素顶部距离视口底部50%的位置(即视口中间线) });
逻辑说明
- 向下滚动:当项目顶部滚动到视口中间(50vh)位置时,立即更新标题为当前项目的
data-title; - 向上滚动:当项目底部离开视口中间位置时,切换到上一个项目的标题,确保标题始终和当前覆盖视口中间的项目对应;
- 处理边界情况:滚动回第一个项目时,自动恢复显示第一个项目的标题。
这样调整后,无论向上还是向下滚动,标题都会和当前对应图片完全同步,满足你“标题仅在对应图片上方时显示”的需求。
内容的提问来源于stack exchange,提问作者Gareth Jones
相关产品推荐
相关产品推荐

