萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 監聽瀏覽器窗口縮放動態切換背景顏色

核心代碼 (5 行)

// 定義切換類的函數
function toggleBgClass() {
  $('body').toggleClass('bgcolor');
}

// 綁定 resize 事件
$(window).on('resize', toggleBgClass);

// 頁面加載時執行一次 (初始化狀態)
toggleBgClass();

CSS 配合

<style>
  /* 默認背景 */
  body { background: #ffffff; transition: background 0.3s; }
  
  /* 窗口寬度 < 800px 時觸發 (需配合 JS 判斷) */
  /* 或由 JS 直接切換類 */
  body.bgcolor { background: #f0f8ff; } /* 淺藍 */
</style>

進階:根據具體寬度閾值切換多種主題

function updateTheme() {
  var width = $(window).width();
  var $body = $('body');
  
  // 移除所有主題類
  $body.removeClass('theme-mobile theme-tablet theme-desktop theme-wide');
  
  if (width < 480) {
    $body.addClass('theme-mobile');
  } else if (width < 768) {
    $body.addClass('theme-tablet');
  } else if (width < 1200) {
    $body.addClass('theme-desktop');
  } else {
    $body.addClass('theme-wide');
  }
}

// 防抖優化:避免 resize 觸發過於頻繁
var resizeTimer;
$(window).on('resize', function() {
  clearTimeout(resizeTimer);
  resizeTimer = setTimeout(updateTheme, 100);
});

// 初始化
updateTheme();

CSS 主題定義

body.theme-mobile   { background: #fff0f0; font-size: 14px; }
body.theme-tablet   { background: #f0fff0; font-size: 15px; }
body.theme-desktop  { background: #f0f0ff; font-size: 16px; }
body.theme-wide     { background: #f5f5f5; font-size: 18px; }

/* 配合響應式佈局 */
@media (max-width: 479px)  { .container { padding: 10px; } }
@media (min-width: 480px)  { .container { padding: 15px; } }
@media (min-width: 768px)  { .container { padding: 20px; } }
@media (min-width: 1200px) { .container { padding: 30px; } }

原生 JS 替代方案 (無 jQuery 依賴)

// 防抖函數
function debounce(fn, delay) {
  var timer;
  return function() {
    var ctx = this, args = arguments;
    clearTimeout(timer);
    timer = setTimeout(function() { fn.apply(ctx, args); }, delay);
  };
}

var updateTheme = function() {
  var width = window.innerWidth;
  document.body.className = document.body.className
    .replace(/theme-\w+/g, '') // 清除舊主題
    .trim();
    
  if (width < 480) document.body.classList.add('theme-mobile');
  else if (width < 768) document.body.classList.add('theme-tablet');
  else if (width < 1200) document.body.classList.add('theme-desktop');
  else document.body.classList.add('theme-wide');
};

window.addEventListener('resize', debounce(updateTheme, 100));
updateTheme(); // 初始化

性能優化提示

  • 防抖/節流:resize 高頻觸發,必須防抖 (100-200ms) 或節流
  • 避免佈局抖動:讀寫分離,先讀 width,再寫 className
  • CSS 媒體查詢優先:純樣式切換用 @media,JS 僅處理邏輯/類切換
  • 被動事件監聽器:window.addEventListener('resize', handler, {passive: true}) 提升滾動性能
copyright © 萬盛學電腦網 all rights reserved