我目前正在尝试使用angularjs应用程序中的IntersectionObserver实现延迟加载。
但是当我向上和向下滚动时,它并不总是调用观察者的回调函数。
我的指示如下:
var app = angular.module("test", []);
app.directive("inViewport", function() {
return {
restrict: "A",
link: function(scope, element, attrs) {
const observer = new IntersectionObserver(callback);
const img = angular.element(element)[0];
observer.observe(img);
function callback(changes) {
changes.forEach(change => {
change.target.classList.toggle(
"visible",
change.intersectionRatio > 0
);
});
}
}
};
});
请参阅this pen了解演示。
答案 0 :(得分:1)
在change.target.classList.toggle中使用 change.isIntersecting 代替 change.intersectionRatio> 0
由于IntersectionObserver以异步方式工作,因此在调用回调函数时会有些迟钝。
var app = angular.module("test", []);
app.directive("inViewport", function() {
return {
restrict: "A",
link: function(scope, element, attrs) {
const observer = new IntersectionObserver(callback);
const img = angular.element(element)[0];
observer.observe(img);
function callback(changes) {
changes.forEach(change => {
change.target.classList.toggle(
"visible",
change.isIntersecting
);
});
}
}
};
});
.main div {
background: green;
height: 100px;
width: 100%;
margin: 10px;
}
.main div.visible {
background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.17/angular.min.js"></script>
<div ng-app="test" class="main">
<div in-viewport=""></div>
<div in-viewport=""></div>
<div in-viewport=""></div>
<div in-viewport=""></div>
<div in-viewport=""></div>
<div in-viewport=""></div>
<div in-viewport=""></div>
<div in-viewport=""></div>
<div in-viewport=""></div>
<div in-viewport=""></div>
</div>