滑鼠移至縮圖上方 → 右側/下方淡入顯示大圖與標題;移開 → 淡出隱藏。適用於相簿、產品展示、圖庫瀏覽。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>縮圖懸停顯示大圖</title>
<style>
.thumbs li { list-style: none; float: left; margin-left: 10px; cursor: pointer; }
.thumbs img { border: 1px solid #000; padding: 2px; margin: 5px; transition: transform 0.2s; }
.thumbs img:hover { transform: scale(1.1); border-color: #007bff; }
.preview { display: none; margin-top: 20px; text-align: center; }
.preview img { max-width: 100%; max-height: 400px; box-shadow: 0 4px 12px rgba(0,0,0,0.15); }
.preview .title { margin-top: 8px; font-weight: bold; color: #333; background: #f0f0f0; padding: 10px; display: inline-block; }
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<ul class="thumbs"></ul>
<div class="preview">
<img id="largeImg" src="" alt="大圖預覽" />
<div class="title" id="imgTitle"></div>
</div>
<script>
// 圖片資料:縮圖路徑 → [大圖路徑, 標題]
var imageData = {
"images/11_s.jpg": ["images/11_b.jpg", "美人 1"],
"images/22_s.jpg": ["images/22_b.jpg", "美人 2"],
"images/33_s.jpg": ["images/33_b.jpg", "美人 3"],
"images/44_s.jpg": ["images/44_b.jpg", "美人 4"]
};
$(function() {
var $thumbs = $('.thumbs');
var $preview = $('.preview');
var $largeImg = $('#largeImg');
var $imgTitle = $('#imgTitle');
// 動態生成縮圖
$.each(imageData, function(thumbSrc, info) {
var $img = $('
')
.attr('src', thumbSrc)
.attr('data-large', info[0])
.attr('data-title', info[1])
.appendTo($thumbs);
});
// 懸停事件
$thumbs.on('mouseenter', 'img', function() {
var $this = $(this);
$largeImg.attr('src', $this.data('large'));
$imgTitle.text($this.data('title'));
$preview.fadeIn('fast');
}).on('mouseleave', 'img', function() {
$preview.fadeOut('fast');
});
});
</script>
</body>
</html>
$thumbs.on('mousemove', 'img', function(e) {
$preview.css({
left: e.pageX + 20,
top: e.pageY + 20
});
});
// 頁面載入時預載大圖
$.each(imageData, function(_, info) {
new Image().src = info[0];
});
$thumbs.on('focusin', 'img', function() { $(this).trigger('mouseenter'); })
.on('focusout', 'img', function() { $(this).trigger('mouseleave'); });
此模式結構清晰:資料配置 → 動態渲染 → 事件委派 → 狀態切換,易於維護擴充,可直接應用於電商產品圖、相簿、作品集等場景。