图像缩放

创建于 2024-12-03 / 23
字体: [默认] [大] [更大]

了解如何创建图像缩放。


图像缩放

鼠标悬停在图片上:

Zoom Preview:

亲自试一试 »


创建图像缩放

步骤 1) 添加 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>

步骤 2) 添加 CSS:

容器必须有 "relative" 定位。

实例

* {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};
  }
}
步骤 4) 启动缩放效果:

实例

<script>
imageZoom("myimage", "myresult");
</script> 亲自试一试 »

0 人点赞过