我正在尝试查找元素何时出现在屏幕上(尝试实现无限加载器)。
为列表中的最后一项绑定(bind)观察者并收听,不幸的是在 chrome 62 mac 10.10 中,即使我正在观察的元素不在视口(viewport)中,回调也会触发。
当我检查相交率时,我可以很容易地阻止它。这是 Intersection Observer 的工作方式吗?
在此先感谢您的帮助。
bindIO();
function ioCallback(entries, observer) {
console.log("entries");
console.log(entries);
entries.forEach(entry => {
// Each entry describes an intersection change for one observed
// target element:
console.log(entry.boundingClientRect);
console.log(entry.intersectionRatio);
console.log(entry.intersectionRect);
console.log(entry.isIntersecting);
console.log(entry.rootBounds);
console.log(entry.target);
console.log(entry.time);
});
}
function bindIO(arguments) {
var options = {
threshold: 1.0
}
observer = new IntersectionObserver(ioCallback, options);
}
var triggerel;
var lastIndex;
var items;
var observer;
setTimeout(function() {
observeEl();
}, 2000);
function observeEl(arguments) {
items = document.querySelectorAll('.item');
lastIndex = items.length
triggerel = items[lastIndex - 1];
observer.observe(triggerel);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0"/>
<title>HTML BolierPlate</title>
<link rel="stylesheet" type="text/css" href="css/reset.css"></link>
<link rel="stylesheet" type="text/css" href="css/mystyle.css"></link>
<style>
.item{
background: green;
margin: 30px;
height: 400px;
width: 400px;
color: black;
font-weight: black;
}
</style>
</head>
<body>
Welcome to BoilerPlate!!!
<div class="item-1 item">
Items #1
</div>
<div class="item-2 item">
Items #2
</div>
<div class="item-3 item">
Items #3
</div>
<div class="item-4 item">
Items #4
</div>
<div class="item-5 item">
Items #5
</div>
<div class="item-6 item">
Items #6
</div>
<div class="item-7 item">
Items #7
</div>
<div class="item-8 item">
Items #8
</div>
<script src="js/lib/jquery.min.js" ></script>
<script src="js/myscript.js" ></script>
</body>
</html>
最佳答案
确实,您触及了一些似乎违反直觉的东西。
当 IntersectionObserver 被实例化时,回调将运行一次以检测元素是否在 View 中(如果不在 View 中,则正确地将相交属性报告为 false)。
最简单的方法是在运行任何只应在元素实际可见时启动的功能之前检查 .isIntersecting
属性。
let observer = new IntersectionObserver(function (entries){
entries.forEach(function(each,index){
if(each.isIntersecting){
console.log(each,each.isIntersecting);
}
})
});
在上述解决方案中,如果 isIntersecting
属性为 true
,您所需的代码将执行一次。并且 isIntersecting
属性为 true
,仅当元素在实例化或目标消失。
希望这有助于确认您在检查这些事情时走在正确的道路上,您没有犯任何错误。
关于javascript - Intersection Observer API 触发回调,即使元素不在 View 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47737137/