$(document).ready(function(){ // 定義視窗寬度變數與斷點 const breakpoint = 450; let previousWidth = $(window).width(); // 初始化函數 - 根據當前窗口大小設置 function initializeLayout() { let windowWidth = $(window).width(); if(windowWidth > breakpoint) { // 大螢幕顯示模式 $('.dropdown-toggle').each(function() { if($(this).next().length > 0) { $(this).next().removeClass('dropdown'); $(this).next().css("display", "flex"); $(this).removeClass("active-arrow"); } }); } else { // 小螢幕顯示模式 $('.dropdown-toggle').each(function() { if($(this).next().length > 0) { $(this).next().addClass('dropdown'); $(this).next().hide(); // 初始化時隱藏下拉選單 $(this).removeClass("active-arrow"); } }); } } // 呼叫初始化函數 initializeLayout(); // 視窗改變事件處理,使用去抖動函數優化效能 let resizeTimer; $(window).resize(function() { clearTimeout(resizeTimer); resizeTimer = setTimeout(function() { let windowWidth = $(window).width(); // 從大螢幕切換到小螢幕 if(previousWidth > breakpoint && windowWidth <= breakpoint) { $('.dropdown-toggle').each(function() { if($(this).next().length > 0) { $(this).next().addClass('dropdown'); $(this).next().hide(); // 自動收起所有下拉選單 $(this).removeClass("active-arrow"); } }); } // 從小螢幕切換到大螢幕 else if(previousWidth <= breakpoint && windowWidth > breakpoint) { $('.dropdown-toggle').each(function() { if($(this).next().length > 0) { $(this).next().removeClass('dropdown'); $(this).next().css("display", "flex"); $(this).removeClass("active-arrow"); } }); } // 在小螢幕尺寸時,每次調整都自動收起選單 if(windowWidth <= breakpoint) { $('.dropdown').hide(); $('.dropdown-toggle').removeClass("active-arrow"); } // 更新前一次的寬度 previousWidth = windowWidth; }, 250); // 250ms 的去抖動時間 }); // 下拉選單點擊事件 - 使用事件委派來處理 $(document).on('click', '.dropdown-toggle', function(e) { let windowWidth = $(window).width(); // 只在移動設備寬度下啟動下拉功能 if(windowWidth <= breakpoint) { e.stopPropagation(); // 檢查下一個元素是否存在 if($(this).next('.dropdown').length > 0) { $(this).next('.dropdown').slideToggle(); $(this).toggleClass("active-arrow"); } } }); // 點擊空白處關閉下拉選單 $(document).on('click', function(e) { let windowWidth = $(window).width(); if(windowWidth <= breakpoint) { var target = e.target; if (!$(target).is('.dropdown-toggle') && !$(target).parents().is('.dropdown-toggle')) { $('.dropdown').slideUp(); $('.dropdown-toggle').removeClass("active-arrow"); } } }); // 特殊情況:當用戶快速調整螢幕尺寸時確保狀態一致 $(window).on('orientationchange', function() { setTimeout(function() { if($(window).width() <= breakpoint) { $('.dropdown').hide(); $('.dropdown-toggle').removeClass("active-arrow"); } }, 100); }); });