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

标签 javascript jquery html css

问题:

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

我目前只能在用户滚动到 div 时启动它,然后当您滚动离开并返回时它会搞砸,我认为这是因为函数再次开始运行。

我想要实现的目标:

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

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

http://jsfiddle.net/annablabber/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>

CSS

.scroll_down {
  margin-bottom: 1000px;
}

.animation_container {
  width: 300px;
  height: 200px;
  background-color: red;
  padding: 30px;
  color: white;
  margin-bottom: 1000px;
}

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 );
    }
  };
} 

对于由视觉设计师清楚地编写的脚本表示歉意。如果匿名代码中的问题不够清楚,请告诉我。

最佳答案

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

var firstScroll = false;

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

function doSomeComplicatedStuff() {

    firstScroll = true;        

    // Your code here
}

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

关于javascript - 如何仅在用户第一次滚动到某个元素时运行自定义函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24791341/

相关文章:

javascript - addclass 函数在 firefox 和 ie 中不起作用

javascript - 搜索字符串中的第一个括号

javascript - 在 WP 中使用 PHP 将 javascript 字符串插入 HTML

javascript - 在 keyup 中设置输入值,停止触发更改事件

html - CSS 按钮将线性渐变背景转换为透明背景

php - 将输入保存到数据库

javascript - 有条件的页面向下滚动

javascript - onload 在 JavaScript 中如何工作?

jQuery 进度条值未设置

javascript - 单击 JQuery 中的按钮打开 UI 对话框