我有一个 div,我想在它滚动到视口(viewport)时更改颜色,我正在尝试使用新的 intersectionObserver
来实现这一点方法。我已经在配置回调中设置了我的参数,但我似乎无法让观察者本身添加类来更改背景颜色?
任何帮助都会很棒。
密码笔: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>
最佳答案
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>
关于javascript - IntersectionObserver 方法不起作用 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48665785/