萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 資料庫 >> 資料庫綜合

jQuery 實現文字無縫左右滾動公告欄:原生 JS 核心邏輯完整解析

從零構建高性能跑馬燈組件

公告欄左右滾動是經典 UI 需求。本文拆解原生 JS 實現核心邏輯,無依賴、可控性強、易於封裝為 jQuery 插件或 Web Component。

HTML 結構與 CSS 佈局

<div id="scrollText">
  <div class="content">這裡是滾動的公告內容...</div>
</div>

#scrollText {
  width: 400px; margin: 0 auto; overflow: hidden; position: relative;
}
.content { position: absolute; white-space: nowrap; }

核心滾動邏輯

var ScrollTime;
function ScrollAutoPlay(contID, scrolldir, showWidth, textWidth, step) {
  var $el = $('#' + contID).children().first(); // 獲取 .content
  var currPos = parseInt($el.css('margin-left')) || 0;

  if (scrolldir === 'left') {
    // 向左滾動:內容向左移出,當完全移出視口寬度時重置到右側
    if (currPos < 0 && Math.abs(currPos) > textWidth) {
      $el.css('margin-left', showWidth);
    } else {
      $el.css('margin-left', currPos - step);
    }
  } else {
    // 向右滾動:內容向右移出,當超出視口右側時重置到左側負寬度
    if (currPos > showWidth) {
      $el.css('margin-left', -textWidth);
    } else {
      $el.css('margin-left', currPos + step); // 注意:原碼此處為 -step,向右應為 +step
    }
  }
}

// 啟動
ScrollTime = setInterval(function() {
  ScrollAutoPlay('scrollText', 'left', 400, $('.content').outerWidth(), 2);
}, 30); // 30ms/幀 ≈ 33fps

// 鼠標懸停暫停
$('#scrollText').hover(
  () => clearInterval(ScrollTime),
  () => ScrollTime = setInterval(...)
);

關鍵參數說明

參數含義
contID容器 ID
scrolldir'left' 或 'right'
showWidth可視區寬度(容器寬度)
textWidth內容實際寬度(需動態獲取)
step每幀移動像素,控制速度

優化建議

  • 使用 requestAnimationFrame 替代 setInterval,幀率更穩、省電。
  • 內容動態更新時重新計算 textWidth 並重置位置。
  • 支持無縫循環:複製內容節點拼接雙倍寬度,滾動至中點瞬時重置,消除跳躍感。
  • 封裝為 $.fn.marquee(options) 插件,暴露 direction/speed/pauseOnHover 等配置。

理解核心邏輯,即可靈活定製符合業務需求的滾動公告組件。

copyright © 萬盛學電腦網 all rights reserved