如何创建:图像缩放
学习如何创建图像缩放。
图像缩放
请将鼠标悬停在图像上:

放大预览:
创建图像缩放
第一步 - 添加 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; /* Itakda ang laki ng DIV na result: */ width: 300px; height: 300px; }
Tatlong hakbang - idagdag ang JavaScript:
function imageZoom(imgID, resultID) { var img, lens, result, cx, cy; img = document.getElementById(imgID); result = document.getElementById(resultID); /* lumikha ng lens: */ lens = document.createElement("DIV"); lens.setAttribute("class", "img-zoom-lens"); /* I-insert ang lens: */ img.parentElement.insertBefore(lens, img); /* Tinitingnan ang proporsyon sa pagitan ng DIV na result at lens: */ cx = result.offsetWidth / lens.offsetWidth; cy = result.offsetHeight / lens.offsetHeight; /* Itakda ang background property sa DIV na result: */ result.style.backgroundImage = "url('" + img.src + "')"; result.style.backgroundSize = (img.width * cx) + "px " + (img.height * cy) + "px"; /* Ipagpapatupad ang kagamitan kapag inililipat ang mouse cursor sa imahe o lens: */ lens.addEventListener("mousemove", moveLens); img.addEventListener("mousemove", moveLens); /* Nakikita rin sa touchscreen: */ lens.addEventListener("touchmove", moveLens); img.addEventListener("touchmove", moveLens); function moveLens(e) {}} var pos, x, y; /* Iwasan ang anumang iba pang operasyon na maaaring mangyari kapag inililipat ang imahe: */ e.preventDefault(); /* Kumuha ng x at y posisyon ng kursor: */ pos = getCursorPos(e); /* Kalkula ang posisyon ng lente: */ x = pos.x - (lens.offsetWidth / 2); y = pos.y - (lens.offsetHeight / 2); /* Iwasan ang lente na nasa labas ng imahe: */ 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;} /* Itakda ang posisyon ng lente: */ lens.style.left = x + "px"; lens.style.top = y + "px"; /* Ipakita ang tinikasan ng lente: */ result.style.backgroundPosition = "-" + (x * cx) + "px -" + (y * cy) + "px"; } function getCursorPos(e) { var a, x = 0, y = 0; e = e || window.event; /* Kumuha ng x at y posisyon ng imahe: */ a = img.getBoundingClientRect(); /* Kalkula ang x at y coordinate ng kursor sa tabi ng imahe: */ x = e.pageX - a.left; y = e.pageY - a.top; /* Isaalang-alang ang anumang pagsasalpok ng pahina: */ x = x - window.pageXOffset; y = y - window.pageYOffset; return {x : x, y : y}; } }
Ika-apat na hakbang - Inisyialisasyon ng pagpapaadlaw:
<script> imageZoom("myimage", "myresult"); </script>