javascript - 如何根据滚动位置触发或停止 jQuery 函数?
问题描述
我正在开发一个网站,该网站有一个标题,当该scrollTop()
值超过浏览器高度的 1/4 时,根据用户是向上还是向下滚动,在屏幕上上下动画。对于主页,标题在所述scrollTop()
值之后更改背景和文本颜色以适应视频背景。
但是,在滚动时headerScrollEvents()
添加“显示”(标题向下滑动)、“隐藏”(标题向上滑动)和“活动”(标题更改背景和文本颜色)类的功能#header
在滚动位置编号时仍在运行小于浏览器高度的 1/4。目标是防止用户从该scrollTop()
值向上滚动到最顶部时添加这些类。
如何在到达某些滚动位置时触发或停止 jQuery 函数?
JS:
function headerScrollEvents() {
var yPos = $(window).scrollTop();
$(window).scroll(function() {
var newYPos = $(this).scrollTop();
if (newYPos > yPos) {
$("#header").removeClass("show active").addClass("hide");
} else {
$("#header").removeClass("hide").addClass("show active");
}
yPos = newYPos;
});
}
$(window).scroll(function() {
if ( $(window).scrollTop() <= $(window).height() / 4 ) {
$("#header").removeAttr("class");
} else if ( $(window).scrollTop() >= $(window).height() / 4 ) {
headerScrollEvents();
}
});
CSS:
#header {
top: 0;
left: 0;
position: fixed;
width: 100%;
z-index: 25;
padding: 48px 0;
transition: transform 500ms ease, background 500ms linear;
background: #000;
}
#header.hide {
transform: translateY(-100%);
}
#header.show {
transform: translateY(0%);
}
#header.active {
background: #fff;
}
解决方案
您可以使用Intersection Observer来代替监听滚动事件。
基于这个例子,我为你创建了一个 jsfiddle。我对其进行了修改以使您正在观看的 div 更大,以便更清楚它是如何工作的。您显然会将 div 的尺寸设置为 0px。
let observer = new IntersectionObserver(entries => {
if (entries[0].boundingClientRect.y < 0) {
console.log("Past the yellow div!");
} else {
console.log("Not past the yellow div");
}
});
observer.observe(document.querySelector("#pixelToWatch"));
body {
padding: 0;
position: relative;
}
#pixelToWatch {
position: absolute;
width: 10px;
height: 10px;
top: 75%;
left: 0;
background: yellow;
}
header {
position: fixed;
width: 100%;
background-color: green;
top: 0;
}
section {
padding-top: 100px;
min-height: 200vh;
background-image: linear-gradient(25deg, red, blue);
color: white;
}
<header>
<p>I'm a header </p>
</header>
<div id="pixelToWatch"> </div>
<section>
<h1>I have a headline </h1>
<p>
And some content
</p>
</section>
<section>
<h1>I have a headline </h1>
<p>
And some content
</p>
</section>
推荐阅读
- sql - SQL - 删除小数并将其值包含在数字中
- sql - 如何使 pg_search 更快?
- google-colaboratory - Colab 的 Huggingface AlBert 标记器 NoneType 错误
- amazon-web-services - AWS NLB 重定向
- firebase - Firestore 安全规则 - 允许基于其父文档数据读取子集合
- ruby-on-rails - 更新 Postgres 后,我的 Rails 服务器日志是黑白的(没有颜色编码的 SQL 操作)
- django - TypeError: context must be a dict 而不是 HttpResponseRedirect: 不使用 test_func() 真的不可能重定向到 url 吗?
- javascript - chartJS:如何在点击时返回最近的 x 轴标签
- php - 如何使用 PHP/MySQL 实现嵌套位置并将其存储在数据库中?
- python - TypeError:**后的 manager_method() 参数必须是映射,而不是 str