当元素已在视口中时触发 IntersectionObserver

2024-01-01

The IntersectionObserver当元素在视口中可见达到一定程度 (0-100%) 时触发。这意味着,当元素是已经 100% 在视口中它不再触发,因为阈值没有变化。

我有一个高度为200vh我想要IntersectionObserver当我滚动时触发over这个元素。因此元素始终 100% 位于视口内。

有没有办法在滚动元素时触发观察者?

我无法使用滚动事件,因为我使用的是 CSSscroll-snap,这会导致事件在 JS 检测到之前被浏览器吞掉。


希望我能够在这里抓住您的挑战,因此我将尝试提出一个适合您的用例的解决方案,即使没有代码可用作参考。

据我了解你正在使用scroll-snap当用户通过滚动进行交互时捕捉部分,您的目的是让 Intersection Observer 在用户从一个部分移动到另一个部分时触发。

在下面的示例中,您将看到如何捕捉部分,但调试器会显示向用户显示哪个部分。

const debuggerSpan = document.querySelector('#current-section');
const sections = [...document.querySelectorAll('.scroll-snap-item')];
const div = document.querySelector('.scroll-snap-container');

/*
 * This method will get called any time a section touches the top
 * of the viewport.
 */
const intersectionDetected = (entries, observer) => {
  entries.forEach((entry) => {
    const {
      innerText
    } = entry.target;

    if (!entry.isIntersecting) return;

    // Making it obvious that the current section is correct.
    debuggerSpan.innerText = innerText;

  });
};

const observer = new IntersectionObserver(intersectionDetected, {

  /*
   * Root should be div and not the default (doc).
   */
  root: div,

  /*
   * Negative margin from the bottom creates an invisible line
   * to detect intersections.
   * 
   * The reason why the recommendation is to use -1% and -99% is to
   * avoid the race condition between two intersections happening
   * (AKA the section about to be out of the viewport and the section
   * about to enter the viewport).
   */
  rootMargin: '-1% 0% -99% 0%',

  /*
   * Default value but making it explicit as this is the 
   * only configuration that works.
   */
  threshold: 0 
});


sections.forEach(section => observer.observe(section));
.scroll-snap-item {
  height: 100vh;
  display: grid;
  place-items: center;
  font-size: 4rem;
  scroll-snap-align: start;
}

.scroll-snap-container {
  scroll-snap-type: y mandatory;
  overflow-y: scroll;
  height: 100vh;
}


/* Decorative stuff below*/

.scroll-snap-item:nth-child(odd) {
  background-color: gray;
}

aside {
  position: fixed;
  font-size: 1.6rem;
  bottom: 16px;
  right: 16px;
  background-color: #333;
  color: white;
  padding: 16px;
  border-radius: 32px;
}
<div class="scroll-snap-container">
  <section class="scroll-snap-item">1</section>
  <section class="scroll-snap-item">2</section>
  <section class="scroll-snap-item">3</section>
  <section class="scroll-snap-item">4</section>
  <section class="scroll-snap-item">5</section>
  <section class="scroll-snap-item">6</section>
</div>

<aside>Current section: <span id="current-section"></span></aside>

我写了几篇实用的文章,涵盖了这一切背后的原因以及解决这种情况的思维过程。如果内容不够清楚,请随时阅读并发表评论:

  • 使用 Intersection Observer API 可以轻松进行滚动监视。 https://wilsotobianco.hashnode.dev/scrollspying-made-easy-with-the-intersection-observer-api/
  • Intersection Observer API 的图形化介绍。 https://wilsotobianco.hashnode.dev/a-graphical-introduction-to-the-intersection-observer-api

这两本书都可以快速阅读,并且应该提供您使用 Intersection Observer 解决这个问题甚至更复杂问题所需的一切。另外,请随意使用我编写的这个工具十字路口观察者游乐场 https://wilsotobianco.com/experiments/intersection-observer-playground/您可以在其中尝试不同的配置并查看它们如何影响交叉点触发器。

希望这有帮助!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当元素已在视口中时触发 IntersectionObserver 的相关文章

随机推荐

  • 登录后出现404.0错误。 Asp.Net MVC 和 IIS 7.5

    我有一个在 IIS 7 5 上运行的 ASP NET MVC 应用程序 已启用表单验证 我可以访问登录页面 这意味着路线没问题 但是当我登录应用程序时应该将发布数据发送到http localhost tgpwebged Account Lo
  • Next.js 与 pkg。语法需要启用以下解析器插件之一:“flow, typescript”

    我使用 next js 与pkg https www npmjs com package pkg在我基于此的项目中tutorial https medium com evenchange4 deploy a commercial next
  • 重画问题

    我的方法中的重绘有问题move 我不知道该怎么做 代码如下 import java awt import java io import java text import java util import javax sound sample
  • 为什么 svn diff 有时会将工作文件复制到临时文件?

    我使用带有 Subversion 的外部 diff 工具 超越比较规则 其中一个很棒的功能是能够在我查看所做的更改时使用 diff 程序对文件进行一些细微的编辑 But svn diff我的不同项目的工作方式有所不同 总之 左侧文件是一个临
  • 带新行的 AlertDialog 消息。 (\n 不起作用。)

    我需要在AlertDialog在安卓上 我已经尝试过使用 n 字符 但它不起作用 我没有看到 n 字符 但文本不会换行 有什么帮助吗 您可以使用跨文本Html fromHtml some string br 在某些文本视图元素上创建新行
  • Android:如何为android活动制作翻转动画,就像iphone从左到右水平翻转一样?

    在我的应用程序中 我想翻转视图 我在iPhone上看过这样的动画 我想在我的 Android 应用程序中实现同样的功能 我想翻转整个活动视图 是否可以 我见过一些 android 中翻转的例子 但在所有示例中 视图都位于同一个活动中 是否可
  • 使用 jquery 禁用右键单击图像

    我想知道如何使用 jQuery 禁用右键单击图像 我只知道这个 这有效 img bind contextmenu function e return false 或者对于较新的 jQuery nearestStaticContainer o
  • Eclipse-导入代码格式设置

    您好 我正在使用 intellij 通过以下步骤添加代码设置 jar 导入设置 然后指向此 JAR 然后右键单击该模块并执行 重新格式化代码 但现在我在 eclipse 中使用相同的项目 如何在clipse和格式代码中使用上述设置jar 除
  • 如何使用robotium生成测试结果报告?

    我一直在使用 Robotium 来测试我的 Android 应用程序 测试成功 但我想知道是否有任何方法可以在单独的文件中查看测试结果 我很幸运 只是像常规 Android JUnit 测试一样运行 robotsium 测试 然后使用标准机
  • 如何设置activemq的队列最大长度

    我想知道是否可以在activemq上配置队列的最大长度 以便当队列的长度达到限制时 入队操作将失败或抛出异常 有人知道这个问题吗 任何帮助将不胜感激 多谢 看一下生产者流程控制http activemq apache org Produce
  • 如何查看 ASP.NET OutputCache 的内容?

    有什么方法可以列出当前存储在 OutputCache 中的页面吗 只需一个路径列表即可 但如果有一种方法可以获取有关每个项目的更多信息 过期等 那就更好了 据我记得缓存是一个单例 每个应用程序域只有一个实例 OutputCache 也使用它
  • MSTest 中 [TearDown] 和 [SetUp] 的替代方案是什么?

    当我使用 MSTest Framework 并复制 Selenium IDE 为我生成的代码时 MSTest 无法识别 TearDown and SetUp 有什么替代方案吗 你会使用 TestCleanup and TestInitial
  • 快速而肮脏的 SQL 字符串转义

    我正在对家庭卷进行最后的润色QueryBuilder具有 postgresql 数据库的 Web 应用程序的类 它用PreparedStatement适用于所有查询 并防止 SQL 注入 然而我想要一种 快速而肮脏 的方式来表示QueryB
  • Grunt JS 复制到网络位置

    我想使用 grunt contrib copy 或任何其他 grunt 复制插件 将文件复制到网络位置 尝试如下 copy test files src Scripts dest location site Scripts 但得到 警告 无
  • 将特殊字符传递给 mailto 正文会导致 JavaScript 崩溃

    我有一个 C ASP NET 应用程序 它为某些用户配置文件信息创建一个 JavaScript 值数组 在客户端 我使用 jQuery JavaScript 读取数组并生成 mailto 链接 某些字段可以包含特殊字符 例如 这是 C 代码
  • 使用值更改清单 screenOrientation

    我正在训练通过资源以恒定值更改清单中的 screenOrientation 这是我的清单的一项活动
  • Neo4J安装-启动服务失败

    我正在尝试安装 Neo4j 1 8 但在启动服务时遇到问题 解压 zip 文件后 我直接进入 bin 文件夹并执行批处理文件 Neo4J bat install SC 创建服务成功 SC 启动服务失败 1053 服务未及时响应启动或控制请求
  • UserPrincipal.GetAuthorizationGroups() 方法出错

    我在 Web 应用程序中使用 UserPrincipal 类的 GetAuthorizationGroups 方法时遇到问题 使用以下代码 我收到 尝试检索授权组时 发生错误 5 PrincipalContext context new P
  • Mockito 测试活动

    我有一个生成事件的类 例如 public class EventSource public addEventListener EventListener listener public raiseEvent Event e listener
  • 当元素已在视口中时触发 IntersectionObserver

    The IntersectionObserver当元素在视口中可见达到一定程度 0 100 时触发 这意味着 当元素是已经 100 在视口中它不再触发 因为阈值没有变化 我有一个高度为200vh我想要IntersectionObserver