萬盛學電腦網

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

jQuery 彈出層完美居中實現(含滾動/縮放自適應)

核心邏輯

通過計算視口尺寸與彈層尺寸差值,設置 position: absolute 配合 scrollTop 實現視覺居中,並監聽滾動與縮放事件動態修正位置。

完整實現代碼

// 顯示並居中彈層
function showDiv(obj) {
    $(obj).show();
    center(obj);
    $(window).scroll(function() { center(obj); });
    $(window).resize(function() { center(obj); });
}

// 計算居中坐標並應用
function center(obj) {
    var windowWidth = document.documentElement.clientWidth;
    var windowHeight = document.documentElement.clientHeight;
    var popupHeight = $(obj).height();
    var popupWidth = $(obj).width();

    $(obj).css({
        "position": "absolute",
        "top": (windowHeight - popupHeight) / 2 + $(document).scrollTop(),
        "left": (windowWidth - popupWidth) / 2
    });
}

// 調用示例
showDiv($("#pop"));

關鍵技術點

  • clientWidth/clientHeight 獲取視口可見區域尺寸
  • scrollTop() 補償頁面滾動偏移,確保絕對定位視覺居中
  • scroll/resize 事件綁定保證窗口變化時實時修正
  • 使用 absolute 而非 fixed 兼容舊版 IE

此方案無需第三方庫,代碼精簡,適合輕量級項目快速集成彈層居中需求。

copyright © 萬盛學電腦網 all rights reserved