进入视口时仅自动滚动嵌入 window 一次。无法向上滚动

Auto-scroll embedded window only once when entering viewport. Can't scroll back up

我将图像嵌入到带有背景图像的容器中,以提供在页面内滚动的效果。最初,我使用这个简单的脚本在页面加载时产生了滚动效果,效果很好。

 $(window).on("load", function () {
    $(".embedded_scroller_image").animate({ scrollTop: $('.embedded_scroller_image')[0].scrollHeight}, 2500, "easeInOutCubic");
}); // end on load 

但是,该元素现在在页面下方太远,我希望该动画在该元素进入视口的 80% 时触发。该部分在这里的代码也可以正常工作(我正在使用滚动限制器来提高浏览器性能)

 // limit scroll call for performance
     var scrollHandling = {
      allow: true,
      reallow: function() {
        scrollHandling.allow = true;
      },
    delay: 500 //(milliseconds) adjust to the highest acceptable value
  };

$(window).on('scroll', function() {
  var flag = true;
    if(scrollHandling.allow) { // call scroll limit
        var inViewport = $(window).height()*0.8; // get 80% of viewport
        $('.embedded_scroller_image').each(function() { // check each embedded scroller
            var distance = $(this).offset().top - inViewport; // check when it reaches offset
            if ($(window).scrollTop() >= distance && flag === true ) {
              $(this).animate({ scrollTop: $(this)[0].scrollHeight}, 2500, "easeInOutCubic"); //animate embedded scroller
              flag = false;
            } 
          });
      } // end scroll limit
  }); // end window scroll function

问题是这样的:我希望自动滚动发生一次然后停止。现在,它适用于进入视口,但如果我随后尝试手动滚动图像,它会一直向下推或断断续续。您无法让元素正常滚动。我试图使用代码中的标志来停止动画,但无法成功运行。

当元素在视口中占 80% 时,如何让这个动画触发,但一次后完全停止?

这也是我模拟的代码笔 http://codepen.io/jphogan/pen/PPQwZL?editors=001 如果向下滚动,您会看到图像元素在进入视口时自动滚动,但如果您尝试在其容器中向上滚动该图像, 不行。

谢谢!

我对你的脚本做了一些调整:

// limit scroll call for performance
var scrollHandling = {
    allow: true,
    reallow: function() { scrollHandling.allow = true; },
    delay: 500 //(milliseconds) adjust to the highest acceptable value
};

$(window).on('scroll', function() {

if(scrollHandling.allow) { // call scroll limit
    var inViewport = $(window).height()*0.8; // get 80% of viewport

    $('.embedded_scroller_image').each(function() { // check each embedded scroller
        var distance = $(this).offset().top - inViewport; // check when it reaches offset

        if ($(window).scrollTop() >= distance ) {
            $(this).animate({ scrollTop: $(this)[0].scrollHeight}, 2500, "easeInOutCubic"); //animate embedded scroller
            scrollHandling.allow = false;
        } 

    });

} // end scroll limit

}); // end window scroll function

我踢掉了你的标志,只是利用了已经声明的scrollHandling.allow。

试试看是否适合你:)

干杯!