我需要创建一个网站,当您将鼠标悬停在图像上时,会显示当前指向的缩放图像。
我已经做到了,但我的问题是你可以用两个箭头改变图像,将你重定向到上一个或下一个图像,当你改变图像时,“缩放图像”不是显示的图像而是初始图像。
如何在不使用任何库的情况下解决这个问题?
function imageZoom(imgID, resultID) {
var img, lens, result, cx, cy;
img = document.getElementById('myimage');
result = document.getElementById(resultID);
lens = document.createElement("DIV");
lens.setAttribute("class", "img-zoom-lens");
img.parentElement.insertBefore(lens, img);
cx = result.offsetWidth / lens.offsetWidth;
cy = result.offsetHeight / lens.offsetHeight;
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();
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;
a = img.getBoundingClientRect();
x = e.pageX - a.left;
y = e.pageY - a.top;
x = x - window.pageXOffset;
y = y - window.pageYOffset;
return {
x: x,
y: y
};
}
}
<div class="img-zoom-container" onmouseover="IsOver(true)" onmouseout="IsOver(false)">
<img id="myimage" src="file:///C:/Users/balda/Desktop/prova%20JS/immagine1.png" onmousemove="imageZoom" width="300" height="300">
</div>
发布于 2019-05-17 16:11:19
据我所知,CSS也可以做到这一点。你根本不需要那么多的JS。您可以使用CSS在悬停时缩放图像。请查看此来源: 链接到示例
https://stackoverflow.com/questions/-100006747
复制相似问题