如何做 - 影像縮放
瞭解如何建立影像縮放。
影像縮放
滑鼠懸停在影像上

縮放預覽
建立影像縮放
步驟 1) 新增 HTML
示例
<div class="img-zoom-container">
<img id="myimage" src="img_girl.jpg" width="300" height="240" alt="女孩">
<div id="myresult" class="img-zoom-result"></div>
</div>
步驟 2) 新增 CSS
容器必須具有“相對”定位。
示例
* {box-sizing: border-box;}
.img-zoom-container {
position: relative;
}
.img-zoom-lens {
position: absolute;
border: 1px solid #d4d4d4;
/*設定鏡頭的尺寸:*/
width: 40px;
height: 40px;
}
.img-zoom-result {
border: 1px solid #d4d4d4;
/*設定結果 DIV 的尺寸:*/
width: 300px;
height: 300px;
}
步驟 3) 新增 JavaScript
示例
function imageZoom(imgID, resultID) {
var img, lens, result, cx, cy;
img = document.getElementById(imgID);
result = document.getElementById(resultID);
/*建立鏡頭:*/
lens = document.createElement("DIV");
lens.setAttribute("class", "img-zoom-lens");
/*插入鏡頭:*/
img.parentElement.insertBefore(lens, img);
/*計算結果 DIV 和鏡頭的比例:*/
cx = result.offsetWidth / lens.offsetWidth;
cy = result.offsetHeight / lens.offsetHeight;
/*設定結果 DIV 的背景屬性*/
result.style.backgroundImage = "url('" + img.src + "')";
result.style.backgroundSize = (img.width * cx) + "px " + (img.height * cy) + "px";
/*當有人將滑鼠移到影像或鏡頭上時執行一個函式:*/
lens.addEventListener("mousemove", moveLens);
img.addEventListener("mousemove", moveLens);
/*同樣適用於觸控式螢幕:*/
lens.addEventListener("touchmove", moveLens);
img.addEventListener("touchmove", moveLens);
function moveLens(e) {
var pos, x, y;
/*阻止在影像上移動時可能發生的任何其他操作*/
e.preventDefault();
/*獲取游標的 x 和 y 位置:*/
pos = getCursorPos(e);
/*計算鏡頭的位置:*/
x = pos.x - (lens.offsetWidth / 2);
y = pos.y - (lens.offsetHeight / 2);
/*防止鏡頭定位在影像外部:*/
if (x > img.width - lens.offsetWidth) {x = img.width - lens.offsetWidth;}
if (x < 0) {x = 0;}
if (y > img.height - lens.offsetHeight) {y = img.height - lens.offsetHeight;}
if (y < 0) {y = 0;}
/*設定鏡頭的位置:*/
lens.style.left = x + "px";
lens.style.top = y + "px";
/*顯示鏡頭“看到”的內容:*/
result.style.backgroundPosition = "-" + (x * cx) + "px -" + (y * cy) + "px";
}
function getCursorPos(e) {
var a, x = 0, y = 0;
e = e || window.event;
/*獲取影像的 x 和 y 位置:*/
a = img.getBoundingClientRect();
/*計算游標的 x 和 y 座標,相對於影像:*/
x = e.pageX - a.left;
y = e.pageY - a.top;
/*考慮任何頁面滾動:*/
x = x - window.pageXOffset;
y = y - window.pageYOffset;
return {x : x, y : y};
}
}