如何創建:圖片放大鏡

學習如何創建圖像放大鏡。

圖片放大鏡

將鼠標懸停在圖像上:

親自試一試

創建圖像放大鏡

第一步 - 添加 HTML:

<div class="img-magnifier-container">
  <img id="myimage" src="img_girl.jpg" width="600" height="400" alt="Girl">
</div>

第二步 - 添加 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;
}

第三步 - 添加 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);
  /* 也適用于觸摸屏: */
  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};
  }
}

第四步 - 啟動放大功能:

<script>
/* 執行放大功能: */
magnify("myimage", 3);
/* 指定圖像的 id 和放大鏡的強度: */
</script>

親自試一試