图片放大镜

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
* {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;
}
</style>
<script>
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>
</head>
<body>

<h1>图像放大镜</h1>

<p>鼠标悬停在图片上:</p>

<div class="img-magnifier-container">
<img id="myimage" src="..." alt="图片" width="600" height="400">
</div>

<p>可以随意更改放大镜的强度</p>

<script>
/* 启动放大功能
带有图像的 ID 和放大镜的强度:*/
magnify("myimage", 7);
</script>

</body>
</html>

 

 

posted @ 2023-10-04 09:55  樱桃树下的约定  阅读(8)  评论(0编辑  收藏  举报
返回顶端