如何仅在用户第一次滚动到某个元素时运行自定义函数?

Ann*_*ber 1 html javascript css jquery

问题:

我有一个花哨的循环图像轮播,当用户滚动到某个 div 时,它需要从特定的第一张幻灯片开始。如果用户向上/向下滚动并返回到该 div,它永远不会重新启动。

我目前只能在用户滚动到 div 时让它启动——然后当你滚动到它时它会被搞砸,我认为这是因为该函数再次开始运行。

我正在努力实现的目标:

  1. 用户滚动到某个 div
  2. 花式图片轮播动画功能运行
  3. 如果用户向上/向下滚动并返回到 div,动画功能将永远不会再次启动。

我的(匿名的,对不起各位!)代码:

http://jsfiddle.net/annalabber/h8pqW/

HTML

<p class="scroll_down">Scroll down...</p>

<div class="animation_container">You should get an alert only once here—the first time you scroll to this div.</div>
Run Code Online (Sandbox Code Playgroud)

CSS

.scroll_down {
  margin-bottom: 1000px;
}

.animation_container {
  width: 300px;
  height: 200px;
  background-color: red;
  padding: 30px;
  color: white;
  margin-bottom: 1000px;
}
Run Code Online (Sandbox Code Playgroud)

jQuery

// The fancy function for my animations
function doSomeComplicatedStuff() {
  alert("...and here's where the complicated animations happen!");
}

// The function to check if div.animation_container is scrolled into view
function isScrolledIntoView(elem)
{
  var docViewTop = $(window).scrollTop();
  var docViewBottom = docViewTop + $(window).height();

  var elemTop = $(elem).offset().top;
  var elemBottom = elemTop + $(elem).height();

return ((elemTop <= docViewBottom) && (elemTop >= docViewTop));
}

// If div.animation_container is scrolled into view, run the fancy function
$(window).on('scroll', function() {
  if (isScrolledIntoView('.animation_container')) {
    run_once(function() {
      doSomeComplicatedStuff();
    });
  }
});

// The function that's supposed to make sure my fancy function will only run ONCE, EVER
function run_once( callback ) {
  var done = false;
  return function() {
    if ( !done ) {
      done = true;
      return callback.apply( this, arguments );
    }
  };
} 
Run Code Online (Sandbox Code Playgroud)

为视觉设计师清楚地编写的脚本道歉。如果匿名代码中的问题不够清楚,请告诉我。

小智 5

将该done变量移动到全局变量中?

var firstScroll = false;

$(window).on('scroll', function() {
  if (isScrolledIntoView('.animation_container') && !firstScroll) {
      doSomeComplicatedStuff();
  }
});

function doSomeComplicatedStuff() {

    firstScroll = true;        

    // Your code here
}
Run Code Online (Sandbox Code Playgroud)

这样,第一次isScrolledIntoView返回 true 时,该doComplicatedStuff函数立即翻转firstScroll停止后续调用的布尔值。