如何創建:圖像縮放

學習如何創建圖像縮放。

圖像縮放

請將鼠標懸停在圖像上:

放大預覽:

親自試一試

創建圖像縮放

第一步 - 添加 HTML:

<div class="img-zoom-container">
  <img id="myimage" src="img_girl.jpg" width="300" height="240" alt="Girl">
  <div id="myresult" class="img-zoom-result"></div>
</div>

第二步 - 添加 CSS:

容器必須具有“相對”定位。

* {box-sizing: border-box;}
.img-zoom-container {
  position: relative;
}
.img-zoom-lens {
  position: absolute;
  border: 1px solid #d4d4d4;
  /*set the size of the lens:*/
  width: 40px;
  height: 40px;
}
.img-zoom-result {
  border: 1px solid #d4d4d4;
  /*set the size of the result div:*/
  width: 300px;
  height: 300px;
}

第三步 - 添加 JavaScript:

function imageZoom(imgID, resultID) {
  var img, lens, result, cx, cy;
  img = document.getElementById(imgID);
  result = document.getElementById(resultID);
  /* 創建 lens: */
  lens = document.createElement("DIV");
  lens.setAttribute("class", "img-zoom-lens");
  /* 插入 lens: */
  img.parentElement.insertBefore(lens, img);
  /* 計算 result DIV 和 lens 之間的比例: */
  cx = result.offsetWidth / lens.offsetWidth;
  cy = result.offsetHeight / lens.offsetHeight;
  /* 為 result 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};
  }
}

第四步 - 初始化放大效果:

<script>
imageZoom("myimage", "myresult");
</script>

親自試一試