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

最佳答案

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

关于javascript - IntersectionObserver并不总是在angularjs指令中触发,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50354876/

10-09 18:43