圖片查看器是電商、相冊、文檔預覽的核心組件。本文提供一個**零依賴、功能完整**的原生 JS 圖片彈窗實現:自適應視窗等比縮放、預加載 Loading、遮罩鎖定、標題欄拖拽移動、鍵盤 ESC 關閉、響應式重計算。
/**
* 計算等比縮放後尺寸
* @param {Object} opts - {width, height, maxWidth, maxHeight}
* @returns {Object} {width, height}
*/
function calcFitSize(opts) {
var w = opts.width, h = opts.height;
var maxW = opts.maxWidth, maxH = opts.maxHeight;
var ratio = Math.min(maxW / w, maxH / h, 1); // 不放大
return { width: Math.round(w * ratio), height: Math.round(h * ratio) };
}
function PopBox(options) {
var opts = Object.assign({
id: 'popBox_' + Date.now(),
width: 650,
height: 'auto',
bgColor: '#fff',
lock: true, // 遮罩
moveHandle: false, // 拖拽手柄選擇器或元素
closeButton: false, // 關閉按鈕選擇器
times: 300, // 動畫時長
shadow: true,
position: 'center', // center / {x, y}
content: '',
onShow: function(){},
onHide: function(){},
onClose: function(){}
}, options);
var $box, $mask, $dragHandle, animating = false;
// 創建 DOM
function create() {
$mask = $('').css({
position: 'fixed', top: 0, left: 0, width: '100%', height: '100%',
background: '#000', opacity: 0.5, zIndex: 9999, display: 'none'
}).appendTo('body');
$box = $('').attr('id', opts.id).css({
position: 'fixed', zIndex: 10000, background: opts.bgColor,
width: opts.width, height: opts.height, display: 'none'
}).appendTo('body');
// 內容區
$box.html('' + opts.content + '');
// 綁定關閉
$mask.add($box.find('.pop-close')).on('click', hide);
$(document).on('keydown.popbox', function(e){ if(e.key==='Escape') hide(); });
// 拖拽
if (opts.moveHandle) {
$dragHandle = $(opts.moveHandle, $box).css('cursor', 'move');
$dragHandle.on('mousedown', startDrag);
}
}
function show() {
if (animating) return;
animating = true;
$mask.fadeIn(opts.times);
center();
$box.fadeIn(opts.times, function(){ animating = false; opts.onShow(); });
$('body').css('overflow', 'hidden'); // 鎖定背景滾動
}
function hide() {
if (animating) return;
animating = true;
$box.fadeOut(opts.times);
$mask.fadeOut(opts.times, function(){
animating = false;
opts.onHide();
opts.onClose();
destroy();
});
$('body').css('overflow', '');
}
function center() {
var w = $box.outerWidth(), h = $box.outerHeight();
var vw = $(window).width(), vh = $(window).height();
$box.css({ left: (vw - w)/2, top: (vh - h)/2 + $(window).scrollTop() });
}
function startDrag(e) {
e.preventDefault();
var startX = e.clientX, startY = e.clientY;
var startL = $box.position().left, startT = $box.position().top;
$(document).on('mousemove.drag', function(e){
$box.css({ left: startL + e.clientX - startX, top: startT + e.clientY - startY });
}).on('mouseup.drag', function(){
$(document).off('mousemove.drag mouseup.drag');
});
}
function destroy() {
$box.remove(); $mask.remove();
$(document).off('keydown.popbox');
}
// 公開 API
this.show = show;
this.hide = hide;
this.setContent = function(html) { $box.find('.pop-content').html(html); };
this.resize = function(w, h) { $box.css({width: w, height: h}); center(); };
// 延遲創建,首次 show 時創建
var initialized = false;
this.show = function() {
if (!initialized) { create(); initialized = true; }
show();
};
}
// 使用示例
function openImageViewer(src) {
var box = new PopBox({
id: 'imgViewer',
width: 900, height: 'auto',
lock: true, shadow: true,
moveHandle: '.pop-title', // 標題欄拖拽
content: '圖片預覽 ×' +
'載入中...' +
'',
onShow: function() {
var $img = $('#imgViewer .pop-img');
var $loading = $('#imgViewer .pop-loading');
var img = new Image();
img.onload = function() {
$loading.hide();
var size = calcFitSize({width: img.width, height: img.height, maxWidth: 900, maxHeight: 750});
$img.attr('src', src).css({width: size.width, height: size.height}).show();
box.resize(size.width, size.height + 40); // +40 標題欄高度
};
img.onerror = function() { $loading.text('加載失敗'); };
img.src = src;
}
});
box.show();
}
.pop-mask { background: rgba(0,0,0,0.6); }
.pop-box { border-radius: 4px; box-shadow: 0 4px 20px rgba(0,0,0,0.3); overflow: hidden; }
.pop-title { height: 40px; line-height: 40px; padding: 0 15px; background: #f5f5f5; border-bottom: 1px solid #ddd; font-weight: bold; }
.pop-close { float: right; font-size: 24px; color: #999; cursor: pointer; line-height: 1; }
.pop-close:hover { color: #333; }
.pop-content { padding: 10px; }
.pop-loading { text-align: center; padding: 50px; color: #999; }
.pop-img { display: block; margin: 0 auto; }
<a href="javascript:openImageViewer('large.jpg')">查看大圖</a>
class PopBox + WeakMap 管理實例。transition + transform: translate(-50%, -50%) 實現 GPU 加速居中。Pointer Events 統一鼠標/觸控。fancybox、viewerjs、lightgallery、react-image-lightbox。從零手寫彈窗組件能深度理解定層、事件流、動畫幀、內存管理等核心前端功力,是通往組件庫作者的必經之路。