如何创建:图像缩放

学习如何创建图像缩放。

图像缩放

请将鼠标悬停在图像上:

放大预览:

본인이 직접 시도해 보세요

创建图像缩放

第一步 - 添加 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;
  /*결과 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 = document.createElement("DIV");
  lens.setAttribute("class", "img-zoom-lens");
  /*렌즈를 삽입합니다: */
  img.parentElement.insertBefore(lens, img);
  /*result DIV와 렌즈 간의 비율을 계산합니다: */
  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>

본인이 직접 시도해 보세요