如何 - 圖片放大鏡
學習如何建立一個圖片放大鏡。
圖片放大鏡
滑鼠懸停在圖片上

建立圖片放大鏡
步驟 1) 新增 HTML
示例
<div class="img-magnifier-container">
<img id="myimage" src="img_girl.jpg" width="600" height="400" alt="女孩">
</div>
步驟 2) 新增 CSS
容器必須具有“相對”定位。
示例
* {box-sizing: border-box;}
.img-magnifier-container {
position: relative;
}
.img-magnifier-glass {
position: absolute;
border: 3px solid #000;
border-radius: 50%;
cursor: none;
/*設定放大鏡的大小:*/
width: 100px;
height: 100px;
}
步驟 3) 新增 JavaScript
示例
function magnify(imgID, zoom) {
var img, glass, w, h, bw;
img = document.getElementById(imgID);
/* 建立放大鏡:*/
glass = document.createElement("DIV");
glass.setAttribute("class", "img-magnifier-glass");
/* 插入放大鏡:*/
img.parentElement.insertBefore(glass, img);
/*為放大鏡設定背景屬性:*/
glass.style.backgroundImage = "url('" + img.src + "')";
glass.style.backgroundRepeat = "no-repeat";
glass.style.backgroundSize = (img.width * zoom) + "px " + (img.height * zoom) + "px";
bw = 3;
w = glass.offsetWidth / 2;
h = glass.offsetHeight / 2;
/* 當有人將放大鏡移到影像上時執行一個函式:*/
glass.addEventListener("mousemove", moveMagnifier);
img.addEventListener("mousemove", moveMagnifier);
/* também para ecrãs táteis: */
glass.addEventListener("touchmove", moveMagnifier);
img.addEventListener("touchmove", moveMagnifier);
function moveMagnifier(e) {
var pos, x, y;
/* 阻止在影像上移動時可能發生的任何其他操作 */
e.preventDefault();
/* 獲取游標的 x 和 y 位置:*/
pos = getCursorPos(e);
x = pos.x;
y = pos.y;
/* 防止放大鏡定位在影像外部:*/
if (x > img.width - (w / zoom)) {x = img.width - (w / zoom);}
if (x < w / zoom) {x = w / zoom;}
if (y > img.height - (h / zoom)) {y = img.height - (h / zoom);}
if (y < h / zoom) {y = h / zoom;}
/* 設定放大鏡的位置:*/
glass.style.left = (x - w) + "px";
glass.style.top = (y - h) + "px";
/* 顯示放大鏡“看到”的內容:*/
glass.style.backgroundPosition = "-" + ((x * zoom) - w + bw) + "px -" + ((y * zoom) - h + bw) + "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};
}
}