【问题标题】:IntersectionObserver method not working - JavascriptIntersectionObserver 方法不起作用 - Javascript
【发布时间】:2018-02-07 14:02:36
【问题描述】:
我有一个 div,我想在它滚动到视口时更改颜色,我正在尝试使用新的 intersectionObserver 方法来实现这一点。我已经在配置回调中设置了参数,但我似乎无法让观察者自己添加类来更改背景颜色?
任何帮助都会很棒。
codepen:https://codepen.io/emilychews/pen/mXVBVK
const config = {
root: null, // sets the framing element to the viewport
rootMargin: '0px',
threshold: 0.5
};
const box = document.getElementById('box');
let observer = new IntersectionObserver(function(entries) {
observer.observe(box);
entries.forEach(function(item){
item.classList.add("active");
});
}, config);
body {
margin: 0; padding: 0;
display:flex;
justify-content: center;
align-items: center;
height: 300vh;
}
#box {
width: 100px;
height: 100px;
background: blue;}
.active {background: red;}
<div id="box"></div>
【问题讨论】:
标签:
javascript
html
scroll
dom-events
intersection-observer
【解决方案1】:
只要交集发生变化,就会调用IntersectionObserver 构造函数中的函数。你不能把observer.observe(box);放在里面。
另外,item 不是 DOM 元素 — 它是IntersectionObserverEntry,所以你不能在上面使用.classList。你可能是想联系item.target。
即使上面的内容被更正了,你的 CSS 也不会改变,因为你已经使用 #box 选择器将 background 设置为 blue,它比 .active 具有更高的特异性。一个简单的解决方法是将#box 更改为.box 并作为HTML 使用<div id="box" class="box"></div>。
修正后的代码如下所示:
const config = {
root: null, // Sets the framing element to the viewport
rootMargin: "0px",
threshold: 0.5
},
box = document.getElementById("box"),
observer = new IntersectionObserver((entries) => entries
.forEach(({target: {classList}}) => classList.add("active")), config);
observer.observe(box);
body {
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 300vh;
}
.box {
width: 100px;
height: 100px;
background: blue;
}
.active {
background: red;
}
<div id="box" class="box"></div>
现在您需要在回调中添加一些逻辑:
entries.forEach(({target: {classList}, intersectionRatio}) => {
if(intersectionRatio > 0.5){
classList.add("active");
}
else{
classList.remove("active");
}
});
这将使<div> 超过 50% 可见时变为红色。
const config = {
root: null, // Sets the framing element to the viewport
rootMargin: "0px",
threshold: 0.5
},
box = document.getElementById("box"),
observer = new IntersectionObserver((entries) => entries
.forEach(({target: {classList}, intersectionRatio}) => {
if(intersectionRatio > 0.5){
classList.add("active");
}
else{
classList.remove("active");
}
}), config);
observer.observe(box);
body {
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 300vh;
}
.box {
width: 100px;
height: 100px;
background: blue;
}
.active {
background: red;
}
<div id="box" class="box"></div>