5

次の Web サイトの機能を模倣しようとしています: www.verbaasd.net。各スクロール「セッション」は、1 つのアクションのみをトリガーします。

ユーザーが下にスクロールするたびに、変数カウントのステータスに応じてアクションが発生します。これがスクロールごとに1回だけ発生するようにします。たとえば、ユーザーがタッチパッド付きの Macbook を持っている場合、非常に広範囲に複数回起動します。カウントはほぼ瞬時に 1 から 4 になります。variabel カウントが 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;
 }

[ジャバスクリプト]

(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 関数」または「requestAnimationframe」を使用する必要があります。

于 2016-04-09T10:12:56.160 に答える