gpt4 book ai didi

javascript - IntersectionObserver : how rootMargin work?

转载 作者:行者123 更新时间:2023-12-01 15:34:31 26 4
gpt4 key购买 nike

当目标元素距离交叉点根 100px 时,我想拦截一个交叉点

enter image description here

为了做到这一点,我将 rootMargin 设置为“100px 0px 100px 0px”。

在这个例子中,当目标元素的第一个像素(红色框)进入交点根时,交点变为

enter image description here

我希望当目标元素距离交叉点根(灰色区域)100px 时,交叉点变为

    var io = new IntersectionObserver(function(entries){
document.getElementById('info').innerHTML = entries[0].isIntersecting ? 'isIntersecting = true' : 'isIntersecting = false';
}, {
rootMargin: '100px 0px 100px 0px'
});
io.observe(document.getElementById('target'));
* {
padding: 0;
margin: 0;
}

.pad {
height: 1000px;
}

#target {
background: rgb(237, 28, 36);
height: 100px;
outline: 100px solid rgba(0,0,0,0.2);
}

#info {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 2rem;
}
<div class="pad"></div>
<div id="target"></div>
<div class="pad"></div>
<span id="info">isIntersecting = true</span>

最佳答案

默认情况下,根是文档视口(viewport),它不是#target 元素的直接祖先。
要使其工作,您必须指定根元素。
根据specification :

Note: rootMargin only applies to the intersection root itself. If atarget Element is clipped by an ancestor other than the intersectionroot, that clipping is unaffected by rootMargin.



var io = new IntersectionObserver(function(entries) {
document.getElementById('info').innerHTML = entries[0].isIntersecting ? 'isIntersecting = true' : 'isIntersecting = false';
}, {
root: document.querySelector('.container'),
rootMargin: '100px 0px 100px 0px'
});
io.observe(document.getElementById('target'));
* {
padding: 0;
margin: 0;
}

.container {
max-height: 300px;
overflow-y: scroll;
}

.pad {
height: 1000px;
}

#target {
background: rgb(237, 28, 36);
height: 100px;
outline: 100px solid rgba(0, 0, 0, 0.2);
}

#info {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 2rem;
}
<div class="container">
<div class="pad"></div>
<div id="target"></div>
<div class="pad"></div>
</div>
<span id="info">isIntersecting = true</span>

检查此 fiddle

关于javascript - IntersectionObserver : how rootMargin work?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58622664/

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