为DOMMouseScroll事件添加延迟

时间:2016-02-29 13:20:33

标签: javascript jquery css

我有一些div应该出现在用户的滚动之后。所以我跟踪mouseScroll事件。但我想为我的活动增加一些延迟。我尝试使用setTimeout但它没有帮助......如果我完整滚动滚轮(每个动作不止一个),除了删除我的班级.shown之外我什么也得不到。我该怎么办?这是我的代码:

$(document).ready(function() {
  var timer;
  var delay = 1000;

  $(window).bind('mousewheel DOMMouseScroll', function(event) {
    var shown = $(".shown").removeClass('shown');
    timer = setTimeout(function() {
      if (event.originalEvent.wheelDelta > 14 || event.originalEvent.detail < 14) {
        // scroll up
        if (shown.next() && shown.next().length) {
          shown.next().addClass('shown');
        } else {
          shown.siblings(":first").addClass('shown');
        }
      } else {
        // scroll down
        if (shown.next() && shown.next().length) {
          shown.next().addClass('shown');

        } else {
          shown.siblings(":first").addClass('shown');
        }
      }
    }, delay);
  }, function() {
    clearTimeout(timer);
  });
});
.view {
  width: 300px;
  height: 20px;
  display: none;
  clear: both;
  transition: opacity 1s ease-out;
  opacity: 0;
}
#first {
  background: grey;
}
#second {
  background: red;
}
#third {
  background: blue;
}
#fourth {
  background: orange;
}
#fifth {
  background: green;
}
.view.shown {
  display: block;
  opacity: 1;
  -webkit-animation: fadeIn 1s;
  animation: fadeIn 1s;
}
@-webkit-keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
<div class="view shown" id="first"></div>
<div class="view" id="second"></div>
<div class="view" id="third"></div>
<div class="view" id="fourth"></div>
<div class="view" id="fifth"></div>

不幸的是,我也不知道如何以相同的延迟来反转这个脚本。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:2)

尝试使用:

  $(window).bind('mousewheel DOMMouseScroll', function(event) {
    var shown = $(".shown").removeClass('shown');
    clearTimeout(timer);
    timer = setTimeout(function() {
      if (event.originalEvent.wheelDelta > 14 || event.originalEvent.detail < 14) {
        // scroll up
        if (shown.next() && shown.next().length) {
          shown.next().addClass('shown');
        } else {
          shown.siblings(":first").addClass('shown');
        }
      } else {
        // scroll down
        if (shown.next() && shown.next().length) {
          shown.next().addClass('shown');

        } else {
          shown.siblings(":first").addClass('shown');
        }
      }
    }, delay);
  });