我在一个盒子上有一个intersectionObserver,当它进入视口时会改变颜色,一切正常。
不过,我正在尝试将其应用于多个框,当我将其更改getElementsById
为querySelectorAll
(JS 的第 13 行)时,它不会打球。
有谁知道我在这里做错了什么?我认为问题不在于intersectionObserver,我认为问题在于选择器。它快把我逼疯了。
代码笔: https ://codepen.io/emilychews/pen/RMWRPZ
window.addEventListener("load", function(){
var iO = "IntersectionObserver" in window; /* true if supported */
if (iO) {
const config = {
root: null, // sets the framing element to the viewport
rootMargin: '400px 0px 0px 0px', // should remove the animation 400px after leaving the viewport
threshold: .5
};
const box = document.getElementById('box1');
// const box = document.querySelectorAll('.box');
let observer = new IntersectionObserver(function(entries) {
entries.forEach(function(item) {
if (item.intersectionRatio > .5) {
item.target.classList.add("active");
} else {
item.target.classList.remove("active");
}
});
}, config);
observer.observe(box);
} // end of if(iO)
}); // end of load event
body {
font-family: arial;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 250vh;
}
.box {
margin: 1rem;
width: 100px;
height: 100px;
background: blue;
opacity: 1;
transition: .5s all;
display: flex;
justify-content: center;
align-items: center;
color: #fff;
}
.active {
background: red;
opacity: 1;
}
<div id="box1" class="box">Box 1</div>
<div id="box2" class="box">Box 2</div>