如何创建:图片放大镜
学习如何创建图像放大镜。
图片放大镜
将鼠标悬停在图像上:
![](/i/photo/hangzhou.jpg)
创建图像放大镜
第一步 - 添加 HTML:
<div class="img-magnifier-container"> <img id="myimage" src="img_girl.jpg" width="600" height="400" alt="Girl"> </div>
第二步 - 添加 CSS:
容器必须具有“相对”定位。
* {box-sizing: border-box;} .img-magnifier-container { position: relative; } .img-magnifier-glass { position: absolute; border: 3px solid #000; border-radius: 50%; cursor: none; /* 设置图像放大器的尺寸 */ width: 100px; height: 100px; }
第三步 - 添加 JavaScript:
function magnify(imgID, zoom) { var img, glass, w, h, bw; img = document.getElementById(imgID); /* 创建放大镜: */ glass = document.createElement("DIV"); glass.setAttribute("class", "img-magnifier-glass"); /* 插入放大镜: */ img.parentElement.insertBefore(glass, img); /* 设置放大镜的背景属性: */ glass.style.backgroundImage = "url('" + img.src + "')"; glass.style.backgroundRepeat = "no-repeat"; glass.style.backgroundSize = (img.width * zoom) + "px " + (img.height * zoom) + "px"; bw = 3; w = glass.offsetWidth / 2; h = glass.offsetHeight / 2; /* 当用户在图像上移动放大镜时执行的函数: */ glass.addEventListener("mousemove", moveMagnifier); img.addEventListener("mousemove", moveMagnifier); /* 也适用于触摸屏: */ glass.addEventListener("touchmove", moveMagnifier); img.addEventListener("touchmove", moveMagnifier); function moveMagnifier(e) { var pos, x, y; /* 防止在图像上移动时可能发生的任何其他操作 */ e.preventDefault(); /* 获取光标的 x 和 y 位置: */ pos = getCursorPos(e); x = pos.x; y = pos.y; /* 防止放大镜位于图像之外: */ if (x > img.width - (w / zoom)) {x = img.width - (w / zoom);} if (x < w / zoom) {x = w / zoom;} if (y > img.height - (h / zoom)) {y = img.height - (h / zoom);} if (y < h / zoom) {y = h / zoom;} /* 设置放大镜的位置: */ glass.style.left = (x - w) + "px"; glass.style.top = (y - h) + "px"; /* 显示放大镜“看到”的内容: */ glass.style.backgroundPosition = "-" + ((x * zoom) - w + bw) + "px -" + ((y * zoom) - h + bw) + "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> /* 执行放大功能: */ magnify("myimage", 3); /* 指定图像的 id 和放大镜的强度: */ </script>