在電商網站看商品圖時,滑鼠移上去會出現一個方框,右側同步顯示該區域的放大影像——這就是放大鏡效果。本文用原生 JS 做一次,並附上思路說明與詳細註解。
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>圖片放大鏡</title>
<style type="text/css">
* { margin: 0px; padding: 0px; }
.small-box {
width: 300px;
height: 300px;
margin-left: 100px;
margin-top: 100px;
border: 1px #ccc solid;
cursor: move;
float: left;
position: relative;
}
.small-box img { width: 300px; height: 300px; }
/* 小圖上的黃色取景框 */
.tool {
width: 150px;
height: 150px;
background-color: gold;
opacity: 0.6;
filter: alpha(opacity=60);
position: absolute;
left: 0px;
top: 0px;
display: none;
}
.tool.active { display: block; }
/* 右側的大圖容器,隱藏溢出實現放大檢視 */
.big-box {
width: 300px;
height: 300px;
border: 1px #ccc solid;
overflow: hidden;
float: left;
margin-top: 100px;
position: relative;
display: none;
}
.big-box.active { display: block; }
.big-box img {
width: 600px;
height: 600px;
position: absolute;
}
</style>
</head>
<body>
<div class="small-box" id="smallBox">
<img src="img1.jpg"/>
<div class="tool" id="tool"></div>
</div>
<div class="big-box" id="bigBox">
<img src="img1.jpg" id="bigImg" />
</div>
<script>
/*
第一步:頁面載入後取得要操作的節點
第二步:為 smallBox 綁定 mouseenter / mouseleave
進入時顯示取景框與大圖,離開時隱藏
第三步:綁定 mousemove
取景框跟著滑鼠走(需做邊界鉗制)
大圖朝反方向、依比例移動
*/
var smallBox = document.getElementById("smallBox"); // 小圖容器
var tool = document.getElementById("tool"); // 黃色取景框
var bigBox = document.getElementById("bigBox"); // 大圖容器
var bigImg = document.getElementById("bigImg"); // 放大後的圖片
// 滑鼠移入,顯示取景框與大圖
smallBox.onmouseenter = function () {
tool.className = "tool active";
bigBox.className = "big-box active";
};
// 滑鼠移出,隱藏
smallBox.onmouseleave = function () {
tool.className = "tool";
bigBox.className = "big-box";
};
// 滑鼠在小圖內移動
smallBox.onmousemove = function (e) {
var _e = window.event || e;
// 讓取景框中心對齊滑鼠
var x = _e.clientX - this.offsetLeft - tool.offsetWidth / 2;
var y = _e.clientY - this.offsetTop - tool.offsetHeight / 2;
// 邊界鉗制:不超出小圖範圍
if (x < 0) { x = 0; }
if (y < 0) { y = 0; }
if (x > this.offsetWidth - tool.offsetWidth) { x = this.offsetWidth - tool.offsetWidth; }
if (y > this.offsetHeight - tool.offsetHeight) { y = this.offsetHeight - tool.offsetHeight; }
tool.style.left = x + "px";
tool.style.top = y + "px";
// 大圖反向移動,位移距離依放大倍率放大(此例 2 倍)
bigImg.style.left = -x * 2 + "px";
bigImg.style.top = -y * 2 + "px";
};
</script>
</body>
</html>
關於事件座標選擇的一段插曲:直覺上會想用 offsetX / offsetY 直接取得相對座標,省掉計算。但實測時取景框會抖動、無法穩定跟隨滑鼠。原因是 onmousemove 會不斷觸發 onmouseover,而後者存在事件傳播,導致 offsetX 的參照對象在不同元素間跳動。改用 clientX - 容器.offsetLeft 計算後,效果就穩定下來了。
這裡我沒有把 CSS、JS 與 HTML 結構分離,純粹是為了方便閱讀與直接運行。

· 把放大倍率抽成變數,而不是到處寫 * 2;
· 大圖尺寸應依「原圖尺寸 ÷ 小圖顯示尺寸」推導,而非寫死;
· 行動裝置沒有 hover,若要支援觸控需改用 touchstart / touchmove。