利用 onmouseover 放大圖片、onmouseout 恢復原尺寸,實現簡單的圖片預覽交互。
<img id="avatar" src="smiley.gif" alt="Smiley" width="32" height="32"
onmouseover="bigImg(this)" onmouseout="normalImg(this)">
<script>
function bigImg(el) {
el.style.height = '64px';
el.style.width = '64px';
}
function normalImg(el) {
el.style.height = '32px';
el.style.width = '32px';
}
</script>
<style>
.zoom-img {
width: 32px; height: 32px;
transition: transform 0.3s ease; /* 平滑動畫 */
transform-origin: center center;
}
.zoom-img:hover {
transform: scale(2); /* 2倍放大,不影響佈局 */
}
</style>
<img class="zoom-img" src="smiley.gif" alt="Smiley">
優勢:無 JS 依賴、GPU 加速動畫、不觸發重排、可控制動畫曲線、響應式友好。
<div class="magnifier">
<img id="source" src="photo.jpg">
<div id="lens"></div>
<div id="preview"></div>
</div>
<style>
.magnifier { position: relative; width: 400px; }
#lens {
position: absolute; width: 100px; height: 100px;
border: 2px solid #fff; background: rgba(0,0,0,0.1);
pointer-events: none; display: none; z-index: 10;
}
#preview {
position: absolute; left: 410px; top: 0; width: 300px; height: 300px;
border: 1px solid #ccc; overflow: hidden; display: none; z-index: 10;
}
#preview img { position: absolute; width: 800px; height: 600px; }
</style>
<script>
const source = document.getElementById('source');
const lens = document.getElementById('lens');
const preview = document.getElementById('preview');
const previewImg = preview.querySelector('img');
source.addEventListener('mousemove', e => {
const rect = source.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
// 鏡頭跟隨(限制在圖片內)
lens.style.left = Math.max(0, Math.min(x - 50, rect.width - 100)) + 'px';
lens.style.top = Math.max(0, Math.min(y - 50, rect.height - 100)) + 'px';
lens.style.display = 'block';
// 預覽區顯示對應放大區域
previewImg.style.left = -lens.style.left.replace('px','') * 3 + 'px';
previewImg.style.top = -lens.style.top.replace('px','') * 3 + 'px';
preview.style.display = 'block';
});
source.addEventListener('mouseleave', () => {
lens.style.display = 'none';
preview.style.display = 'none';
});
</script>
簡單放大用 CSS transform: scale() + transition 最佳;複雜放大鏡需 JS 計算座標映射。理解兩種方案適用場景,選擇最適合業務的實現方式。