JavaScript 滚动时淡入一旦淡入不淡出

JavaScript Fade in on scroll once faded in don't fade out

只是一个简单的问题,完全是新手 JavaScript 但我正在学习!我有这段代码,当元素的值为 data-animate-in="fadeIn" data-animate-in-delay="100" 时,它们会在滚动时淡入。一切正常,我遇到的唯一问题是,当我向下滚动页面时,它们现在正在淡出……有没有办法让它在第一次淡出后保持稳定。

这是我的代码

JavaScript

    $(function() {

  var html = $('html');

  // On Screen

  $.fn.isOnScreen = function() {
    var elementTop = $(this).offset().top,
      elementBottom = elementTop + $(this).outerHeight(),
      viewportTop = $(window).scrollTop(),
      viewportBottom = viewportTop + $(window).height();
    return elementBottom > viewportTop && elementTop < viewportBottom;
  };

  function detection() {
    for (var i = 0; i < items.length; i++) {
      var el = $(items[i]);

      if (el.isOnScreen()) {
        el.addClass("in-view");
      } else {
        el.removeClass("in-view");
      }
    }
  }

  var items = document.querySelectorAll(
    "*[data-animate-in], *[data-detect-viewport]"
  ),
    waiting = false,
    w = $(window);

  w.on("resize scroll", function() {
    if (waiting) {
      return;
    }
    waiting = true;
    detection();

    setTimeout(function() {
      waiting = false;
    }, 100);
  });

  $(document).ready(function() {
    setTimeout(function() {
      detection();
    }, 500);

    for (var i = 0; i < items.length; i++) {
      var d = 0,
        el = $(items[i]);
      if (items[i].getAttribute("data-animate-in-delay")) {
        d = items[i].getAttribute("data-animate-in-delay") / 1000 + "s";
      } else {
        d = 0;
      }
      el.css("transition-delay", d);
    }
  });
});

CSS

    /* -- Animation -- */

[data-animate-in] {
    opacity: 0;
    transition: transform 0.8s ease, opacity 0.8s ease
}

[data-animate-in="up"] {
    transform: translate3d(0, 24px, 0)
}

[data-animate-in="left"] {
    transform: translate3d(-25%, 0, 0)
}

[data-animate-in="right"] {
    transform: translate3d(25%, 0, 0)
}

[data-animate-in="down"] {
    transform: translate3d(0, -24px, 0)
}

[data-animate-in="fadeIn"] {
    transform: translate3d(0, 0, 0)
}

[data-animate-in].in-view {
    opacity: 1;
    transform: translate3d(0, 0, 0);
    -webkit-transform: translate3d(0, 0, 0);
    transition: transform 0.6s ease, opacity 0.6s ease
}

.fade-in {
    opacity: 0;
    transition: opacity 1s ease
}

.page-loaded .fade-in,.page-loaded.fade-in {
    opacity: 1
}

对我的代码有任何建议或改进,请告诉我。刚开始会有帮助!

谢谢:)

如我的评论所述,我建议在元素进入视口且动画完成后删除 data-animate-in 属性。删除属性需要延迟执行,因为 CSS 规则也引用该属性,直接删除它会使元素失去 CSS 规则。这可以通过 window.setTimeout():

完成
if (el.isOnScreen()) {
    el.addClass("in-view");
    setTimeout(function() {
      this.removeAttr('data-animate-in');
    }.bind(el), 800);
  } else {
    el.removeClass("in-view");
  }

我使用 800 毫秒作为延迟,因为 CSS 动画也设置为 0.8 秒:

transition: transform 0.8s ease, opacity 0.8s ease

如果您想更改持续时间,请同时更改延迟以匹配过渡。

可以找到更新的 Fiddle here