Javascript:在视口中设置动画Div

时间:2017-09-16 07:01:51

标签: javascript css

在图片中,您会在标题下方看到4个圆圈,

我无法弄清楚当它们在视口中时如何使它们成为动画

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

您可以使用Intersection_Observer_API检查元素何时在视口中并应用动画。

https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API

function handleIntersectionEntry(entry) {
if (entry.length > 0) {
  const item = entry[0];
  const ratio = Math.floor(item.intersectionRatio);
  if (ratio > 0) {
    // ITEM IN VIEWPORT
  } else if (ratio < 1) {
   // ITEM OUT OF VIEWPORT
  }
}


  const config = {
    root: null,
    threshold: [1.0],
    rootMargin: "0px"
  };

  this.Observer = new IntersectionObserver(
    handleIntersectionEntry,
    config
  );

  this.Observer.observe('YOUR DOM ELEMENT TO MONITOR');

Polyfill支持所有浏览器:https://github.com/w3c/IntersectionObserver/tree/master/polyfill