作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
当目标元素距离交叉点根 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>
最佳答案
默认情况下,根是文档视口(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>
关于javascript - IntersectionObserver : how rootMargin work?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58622664/
当目标元素距离交叉点根 100px 时,我想拦截一个交叉点 为了做到这一点,我将 rootMargin 设置为“100px 0px 100px 0px”。 在这个例子中,当目标元素的第一个像素(红色框
设置rootMargin的代码如下所示。 let observerOptions = { root: null, rootMargin: "100px", threshold:
我是一名优秀的程序员,十分优秀!