[英]IntersectionObserver rootMargin's positive and negative values are not working
[英]IntersectionObserver: how rootMargin work?
当目标元素距离交叉点根 100px 时,我想拦截一个交叉点
为了做到这一点,我将 rootMargin 设置为“100px 0px 100px 0px”。
在这个例子中,当目标元素的第一个像素(红色框)进入交点根时,交点变为
我希望当目标元素距离交叉点根(灰色区域)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>
默认情况下,根是文档视口,它不是#target 元素的直接祖先。
要使其工作,您必须指定根元素。
根据规格:
注意:rootMargin 仅适用于交集根本身。 如果目标元素被交叉根以外的祖先裁剪,则该裁剪不受 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'));
<div class="container">
<div class="pad"></div>
<div id="target"></div>
<div class="pad"></div>
</div>
<span id="info">isIntersecting = true</span>
* {
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;
}
检查这个小提琴
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.