5

我正在尝试模仿以下网站的功能:www.verbaasd.net。每个滚动“会话”只会触发一个动作。

每次用户向下滚动时,都会发生一个动作,具体取决于变量计数的状态。我只希望每次滚动发生一次。例如,如果用户有一台带触摸板的 Macbook,它会触发多次,非常大。计数会立即从 1 变为 4。有没有办法设置超时或其他东西,以便在变量计数增加或减少 1 时停止 0.5 秒?

当前代码:

var count = 1;

$(window).on('mousewheel DOMMouseScroll', function(e) {
  if (e.originalEvent.wheelDelta / 120 > 0) {
    count -= 1;
  } else {
    count += 1;
  }
  if (count < 1) count = 1;
  if (count > 4) count = 4;

    switch (count) {
    case 1:
      // do something
      break;
    case 2:
      // do something
      break;
    case 3:
      // do something
      break;
    case 4:
      // do something
      break;
  }

  $(".cd-background-wrapper").attr("data-slide", count);

});
4

2 回答 2

1

我推荐其他方式。

您应该使用“preventDefault”和使用 setTimeout 的延迟效果。

我在链接下面写了一个简单的原型代码。(仅在 Chrome 和 safari 上测试过)

http://codepen.io/nigayo/pen/PNEvmY

[HTML]

 <body>
  <div id="wrap">
    <section>section A</section>
    <section>section B</section>
    <section>section C</section>
    <section>section D</section>
  </div>
</body>

[CSS]

 body {
   overflow: hidden;
   height: 100%;
 }

 #wrap {
   position: relative;
   width: 100%;
   height: 100%;
   top: 0;
 }

 section {
   width: 100%;
   height: 600px;
 }

 section:nth-child(1) {
   background: red;
 }
 section:nth-child(2) {
   background: blue;
 }

 section:nth-child(3) {
   background: green;
 }
 section:nth-child(4) {
   background: magenta;
 }

[JavaScript]

(function() {
  var currentPanel = 1;
  var wrap = $('#wrap');
  var panelsize = 600;
  var step = 10;
  var interval = 1000;
  var direction = 1;

  var bAnimation = false;

  function animation() {
    setTimeout(function() {
      var currentTop = parseInt(wrap.css("top"));

      if (direction < 0) {
        if (currentTop <= minValue) {
          setTimeout(function() {
            bAnimation = false;
          }, interval);
          return;
        }
      } else {
        if (currentTop >= minValue) {
          setTimeout(function() {
            bAnimation = false;
          }, interval);
          return;
        }
      }

      wrap.css({
        "top": currentTop - step
      });
      animation();
    }, 16);
  }

  $(window).bind('mousewheel DOMMouseScroll', function(event) {
    event.preventDefault();
    if (bAnimation) return;

    var currentTop = parseInt(wrap.css("top"));

    if (event.originalEvent.wheelDelta < 0) {
      //down scroll
      minValue = currentTop - panelsize;
      step = 10;
      direction = -1;
    } else {
      //up scroll
      minValue = currentTop + panelsize;
      step = -10;
      direction = 1;
    }

    console.log(minValue, bAnimation);
    bAnimation = true;
    animation();
  });
})();

如果你参考我的代码,你应该使用 'jquery animate function' 或 'requestAnimationframe' 作为动画逻辑。

于 2016-04-09T10:12:56.160 回答
0

感谢 A. Wolff。使用 _.throttle 和 lodash.js 成功了!您可以在此处找到更多信息:https ://css-tricks.com/the-difference-between-throttling-and-debouncing/

于 2016-04-09T11:03:40.643 回答