0

我目前正在尝试在我的 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
          );
        });
      }
    }
  };
});

请参阅这支笔进行演示。

4

1 回答 1

2

在 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>

于 2019-03-13T02:50:34.663 回答