javascript - IntersectionObserver:找出元素何时在视口之外
问题描述
使用IntersectionObserver API,我如何找出特定元素何时在视口之外?
一旦用户滚动过标题,并且标题因此不再位于视口内,我需要输出控制台日志。我想使用IntersectionObserver
而不是滚动事件侦听器来最小化负载,因为它是异步工作的。我到目前为止的代码是:
let options = {
root: null, //root
rootMargin: '0px',
threshold: 1.0,
};
function onChange(changes, observer) {
changes.forEach(change => {
if (change.intersectionRatio < 0) {
console.log('Header is outside viewport');
}
});
}
let observer = new IntersectionObserver(onChange, options);
let target = document.querySelector('#header');
observer.observe(target);
此代码不输出任何控制台日志。PS:我的<header>
元素的 ID 为header
.
解决方案
您的代码中有两个问题:
你
options.threshold
被定义为“1”。这意味着onChange
总是在intersectionRatio
值从 <1 变为 1 时执行,反之亦然。但你真正想要的是一个threshold
“0”。intersectionRatio
永远不会低于 0。因此,您必须将if
子句中的条件更改为change.intersectionRatio === 0
。
推荐阅读
- scala - 如何使用正则表达式在scala中提取匹配字符串?
- git - VSCode:如何在终端而不是弹出窗口/选项卡中询问密码?
- html - flexbox 中的表格无法滚动
- c++ - 在 Qt 中实现无限缩放画布
- java - 添加Mybatis-spring-boot-starter到Maven报错
- php - 如何在刀片 laravel 中发送会话
- c# - 在 linq where 子句中使用方法返回值
- javascript - 在 JavaScript 中独立运行 JavaScript 代码?
- python - 如何在 pandas 数据框中编写以下 SQL 语句?
- sql-server - ssis中整个过程中带有日期的静态文件名