DIV CSS 佈局教程網

解決 onmousewheel 事件被連續觸發導致整屏切換錯亂
編輯:關於JavaScript     

想做一個「滾動一行滾輪就整屏切換」的首屏/次屏效果,看似簡單,實作時卻踩了不少坑。最惱人的一個是:在 Chrome 上 onmousewheel 會一口氣觸發好幾次,動畫還沒跑完就又被呼叫,於是出現滾到底卻翻不過去、或一次跳兩屏的窘境。以下記錄整個排查與收斂的過程。

第一版:直觀但會出問題

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<style>
  div { width: 700px; height: 1000px; }
  .red { background-color: red; }
  .yellow { background-color: yellow; }
</style>
</head>
<body>
<div class="red"></div>
<div class="yellow"></div>
<div class="red"></div>
<div class="yellow"></div>
<div class="red"></div>
<script src="../jQuery/jquery.min.js"></script>
<script src="test.js"></script>
</body>
</html>
$(document).ready(function(){
  var height = $(window).height();

  var scrollFunc = function(e){
    var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
    e = e || window.event;
    if ((e.wheelDelta < 0 || e.detail > 0) && scrollTop >= 0 && scrollTop < height) {
      $(document.body).animate({scrollTop: height}, "fast");
      $(document.documentElement).animate({scrollTop: height}, "fast");
    } else if ((e.wheelDelta > 0 || e.detail < 0) && scrollTop >= height && scrollTop <= height + 20) {
      $(document.body).animate({scrollTop: 0}, "fast");
      $(document.documentElement).animate({scrollTop: 0}, "fast");
    }
  };

  if (document.addEventListener) {
    document.addEventListener('DOMMouseScroll', scrollFunc, false);
  }
  window.onmousewheel = document.onmousewheel = scrollFunc;
});

這段在 IE 與 Firefox 上測試都正常,Chrome 卻會重複觸發。原因是使用者滾動滾輪往往一次就滑出很大的幅度,導致 scrollFunc 被連續呼叫,而前一次 animate 還沒結束,新的又疊上去,動畫互相打架。

第二版:動畫期間先解除綁定

$(document).ready(function(){
  var height = $(window).height();

  var scrollFunc = function(e){
    document.onmousewheel = undefined;   // 先關掉
    var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
    e = e || window.event;

    if ((e.wheelDelta < 0 || e.detail > 0) && scrollTop >= 0 && scrollTop < height) {
      $(document.body).animate({scrollTop: height}, "fast", "linear", function(){
        document.onmousewheel = scrollFunc;   // 動畫結束再開回來
      });
      $(document.documentElement).animate({scrollTop: height}, "fast", "linear", function(){
        document.onmousewheel = scrollFunc;
      });
    } else if ((e.wheelDelta > 0 || e.detail < 0) && scrollTop >= height && scrollTop <= height + 20) {
      $(document.body).animate({scrollTop: 0}, "fast", "linear", function(){
        document.onmousewheel = scrollFunc;
      });
      $(document.documentElement).animate({scrollTop: 0}, "fast", "linear", function(){
        document.onmousewheel = scrollFunc;
      });
    }
  };

  if (document.addEventListener) {
    document.addEventListener('DOMMouseScroll', scrollFunc, false);
  }
  document.onmousewheel = scrollFunc;
});

能跑了,但解除/重綁的寫法既不優雅也容易漏,特別是 DOMMouseScroll 那條路徑根本沒被鎖住。

第三版:用旗標控制,順便收斂冗餘

$(document).ready(function(){
  var height = $(window).height();
  var body = (navigator.userAgent.indexOf("Firefox") > 0 ||
              navigator.userAgent.indexOf("MSIE") > 0)
             ? document.documentElement : document.body;

  var isFinish = true;

  var scroll = function(target){
    isFinish = false;
    $(body).animate({scrollTop: target}, "fast", "linear", function(){
      isFinish = true;
    });
  };

  var scrollFunc = function(e){
    if (!isFinish) return;          // 動畫進行中,直接忽略
    var scrollTop = body.scrollTop;
    e = e || window.event;

    if ((e.wheelDelta < 0 || e.detail > 0) && scrollTop >= 0 && scrollTop < height - 20) {
      scroll(height);
    } else if ((e.wheelDelta > 0 || e.detail < 0) && scrollTop >= height && scrollTop <= height + 20) {
      scroll(0);
    }
  };

  if (navigator.userAgent.indexOf("Firefox") > 0) {
    document.addEventListener('DOMMouseScroll', scrollFunc, false);
  } else {
    document.onmousewheel = scrollFunc;
  }
});

這個問題帶走的三個經驗

第一,凡是「事件觸發後啟動動畫」的場景,都要有互斥鎖,這裡用一個 isFinish 旗標就足夠,比解除再重綁事件乾淨得多。第二,滚輪方向的判斷在不同瀏覽器上要靠 wheelDelta 與 detail 兩組值互補,只寫一邊難免出錯。第三,scrollTop 的讀取要同時考慮 documentElement 與 body,這也是跨瀏覽器的老問題。

如果今天重寫,我會直接用 wheel 事件並在處理函數開頭呼叫 preventDefault(),再搭配 requestAnimationFrame 做節流,程式碼會比這三個版本加起來還短。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved