gpt4 book ai didi

javascript - 配置 IntersectionObserver 以根据 X 像素更改 *.isIntersecting 的值

转载 作者:行者123 更新时间:2023-11-30 20:58:54 25 4
gpt4 key购买 nike

我有 intersection observer object 它可以工作,但我希望它在某个元素超过或位于交点底部 100 像素时通知我。

使用默认配置,一旦元素正好在 View 中,它只会更改 .isIntersection 的值。但是当元素在视口(viewport)上方或下方 100 像素时,我想做一些事情。

这是我的代码:

var iObserver = new IntersectionObserver(function(element) {
console.log('elementi', element); // I want to trigger here when elementi is 100px or less of distance to the viewport.
});

var el;
for (var i = 0; i < elements.length; i++) {
el = elements[i];
console.log('eli', el);
iObserver.observe(el);
}

更新

感谢用户的回答我使用了这个并且它有效:

var iObserver = new IntersectionObserver(function(entryEvent) {
//...
}, {'rootMargin': '100px 0px 100px 0px'});

最佳答案

您可以在传递给观察者的选项中定义 rootMargin 顶部和底部。

在演示中,将红色矩形悬停在距 .container 10px 的距离时,将调用观察者:

const options = {
root: document.querySelector('.container'),
rootMargin: '10px 0px 10px 0px',
};

let i = 0;

const iObserver = new IntersectionObserver((entries) => console.log(`intersection ${i++}`), options);

iObserver.observe(document.querySelector('.element'));
.container {
position: relative;
height: 20px;
background: lightblue;
}

.element {
position: absolute;
top: calc(100% + 30px);
height: 100px;
width: 100px;
background: red;
margin-bottom: 20px;
transition: top 5s;
}

.element:hover {
top: calc(100% - 30px);
}

.as-console-wrapper {
height: 50px;
}
<div class="container">
<div class="element">1</div>
</div>

关于javascript - 配置 IntersectionObserver 以根据 X 像素更改 *.isIntersecting 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47329289/

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