如何创建:图像缩放
- Kuwanan girmi: shafin na sau Kuwanan girmi: kundin da za a iya fara sa ido
- Kuwanan girmi: shafin na sau Kuwanan girmi: kudin tsofiin
学习如何创建图像缩放。
图像缩放
请将鼠标悬停在图像上:

放大预览:
创建图像缩放
第一步 - 添加 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; /* mayar saukar da saukar DIV result: */ width: 300px; height: 300px; }
kiwa na uku - ayya JavaScript:
function imageZoom(imgID, resultID) { var img, lens, result, cx, cy; img = document.getElementById(imgID); result = document.getElementById(resultID); /* mayar lens: */ lens = document.createElement("DIV"); lens.setAttribute("class", "img-zoom-lens"); /* mayar lens: */ img.parentElement.insertBefore(lens, img); /* takaita kwararren result DIV da lens: */ cx = result.offsetWidth / lens.offsetWidth; cy = result.offsetHeight / lens.offsetHeight; /* mayar da background properties ga DIV result: */ result.style.backgroundImage = "url('" + img.src + "')"; result.style.backgroundSize = (img.width * cx) + "px " + (img.height * cy) + "px"; /* yana aiki a hanyar kura ko'fya dake ko'fya ko'fya: */ lens.addEventListener("mousemove", moveLens); img.addEventListener("mousemove", moveLens); /* kuma kuma yana iya yiwa kaiyuka: */ 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>
- Kuwanan girmi: shafin na sau Kuwanan girmi: kundin da za a iya fara sa ido
- Kuwanan girmi: shafin na sau Kuwanan girmi: kudin tsofiin