什麼是scroll事件?

當用户滾動指定的元素時,會發生scroll事件。這個事件適用於所有可滾動的元素和window對象(瀏覽器窗口)

scroll()方法語法

// 觸發被選元素的scroll事件
$(selector).scroll();

// 添加函數到scroll事件
$(selector).scroll(function() {
  // 事件處理代碼
});

🧪 實用代碼示例

1️⃣ 基礎滾動事件監聽(監聽窗口滾動)

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>基礎scroll事件示例</title>
  <style>
    body { height: 2000px; }
    .scroll-info { 
      position: fixed; 
      top: 20px; 
      right: 20px;
      background: #333;
      color: white;
      padding: 10px;
      border-radius: 5px;
    }
  </style>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
  <div class="scroll-info">滾動位置: <span id="scrollPos">0</span></div>
  
  <script>
    $(window).scroll(function() {
      var scrollPos = $(window).scrollTop();
      $('#scrollPos').text(scrollPos);
      
      // 滾動到100px以上顯示提示
      if (scrollPos > 100) {
        $('.scroll-info').css('background', '#4CAF50');
      } else {
        $('.scroll-info').css('background', '#333');
      }
    });
  </script>
</body>
</html>

效果:頁面滾動時,右上角會顯示當前滾動位置,當滾動超過100px時,提示背景變綠。


2️⃣ 返回頂部按鈕效果(最常用場景!)

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>返回頂部按鈕示例</title>
  <style>
    body { height: 2000px; }
    .goTop {
      position: fixed;
      right: 20px;
      bottom: 20px;
      background: #333;
      color: white;
      width: 40px;
      height: 40px;
      border-radius: 50%;
      text-align: center;
      line-height: 40px;
      cursor: pointer;
      display: none;
      transition: all 0.3s;
    }
    .goTop:hover {
      background: #4CAF50;
    }
  </style>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
  <div class="goTop">↑</div>
  
  <script>
    $(window).scroll(function() {
      // 滾動超過400px顯示返回按鈕
      if ($(window).scrollTop() > 400) {
        $('.goTop').fadeIn();
      } else {
        $('.goTop').fadeOut();
      }
    });
    
    // 點擊返回按鈕返回頂部
    $('.goTop').click(function() {
      $('html, body').animate({ scrollTop: 0 }, 300);
    });
  </script>
</body>
</html>

效果:當頁面滾動超過400px時,右下角會出現一個"↑"按鈕,點擊後頁面平滑滾動回頂部。


3️⃣ 導航欄固定效果(滾動到一定位置時固定)

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>導航欄固定效果</title>
  <style>
    body { height: 2000px; }
    .navbar {
      width: 100%;
      height: 60px;
      background: #333;
      color: white;
      text-align: center;
      line-height: 60px;
      transition: all 0.3s;
    }
    .navbar.fixed {
      position: fixed;
      top: 0;
      box-shadow: 0 2px 5px rgba(0,0,0,0.2);
      z-index: 1000;
    }
  </style>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
  <div class="navbar">導航欄</div>
  
  <script>
    $(window).scroll(function() {
      var scrollPos = $(window).scrollTop();
      
      // 滾動超過150px時固定導航欄
      if (scrollPos > 150) {
        $('.navbar').addClass('fixed');
      } else {
        $('.navbar').removeClass('fixed');
      }
    });
  </script>
</body>
</html>

效果:當頁面滾動超過150px時,導航欄會固定在頁面頂部,並添加陰影效果。


4️⃣ 滾動到底部加載更多內容

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>滾動加載更多內容</title>
  <style>
    body { height: 3000px; }
    #content { 
      margin: 20px;
      border: 1px solid #ccc;
      padding: 20px;
      min-height: 500px;
    }
    #loading { 
      text-align: center; 
      padding: 20px; 
      display: none;
    }
  </style>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
  <div id="content">
    <h2>內容區域</h2>
    <p>這裏是一些初始內容...</p>
  </div>
  <div id="loading">加載更多內容...</div>
  
  <script>
    var isLoading = false;
    var page = 1;
    
    $(window).scroll(function() {
      // 檢查是否滾動到頁面底部
      if (!isLoading && $(window).scrollTop() + $(window).height() >= $(document).height() - 200) {
        isLoading = true;
        $('#loading').show();
        
        // 模擬加載更多內容
        setTimeout(function() {
          page++;
          var newContent = '<p>這是第 ' + page + ' 頁的內容...</p>';
          $('#content').append(newContent);
          $('#loading').hide();
          isLoading = false;
        }, 1000);
      }
    });
  </script>
</body>
</html>

效果:當頁面滾動到接近底部時,顯示"加載更多內容",然後模擬加載新內容。

⚠️ 常見問題及解決方案

1. 為什麼scroll事件不觸發?

根據知識庫[1],常見原因有:

  • 事件冒泡問題:檢查是否有其他事件處理器阻止了事件的冒泡
  • 動態加載內容:如果內容是動態加載的,確保在內容加載完成後綁定事件
  • 綁定對象錯誤:確保使用$(window).scroll()監聽窗口滾動,而不是$('body').scroll()

2. 如何正確監聽窗口滾動?

// 正確方式:監聽窗口滾動
$(window).scroll(function() {
  // 處理滾動事件
});

// 錯誤方式:監聽body滾動(通常不會觸發,因為body沒有滾動條)
$('body').scroll(function() {
  // 這個不會工作
});

3. 如何獲取滾動位置?

// 獲取窗口滾動位置(從頂部開始的距離)
var scrollPos = $(window).scrollTop();

// 獲取元素的滾動位置
var elementScrollPos = $('#myElement').scrollTop();

💡 小貼士

  1. 性能優化:滾動事件處理函數不要做太複雜的操作,避免頁面卡頓。可以考慮使用debounce函數來限制執行頻率。
  2. 現代瀏覽器:scroll事件在現代瀏覽器中表現良好,但要注意在移動設備上的表現。
  3. 替代方案:對於需要精確控制的滾動效果,可以考慮使用requestAnimationFrame