首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >鼠标悬停在JS时如何缩放图像?

鼠标悬停在JS时如何缩放图像?
EN

Stack Overflow用户
提问于 2019-05-17 07:04:59
回答 1查看 0关注 0票数 0

我需要创建一个网站,当您将鼠标悬停在图像上时,会显示当前指向的缩放图像。

我已经做到了,但我的问题是你可以用两个箭头改变图像,将你重定向到上一个或下一个图像,当你改变图像时,“缩放图像”不是显示的图像而是初始图像。

如何在不使用任何库的情况下解决这个问题?

代码语言:javascript
复制
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
    };
  }
}

代码语言:javascript
复制
<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>
EN

回答 1

Stack Overflow用户

发布于 2019-05-17 16:11:19

据我所知,CSS也可以做到这一点。你根本不需要那么多的JS。您可以使用CSS在悬停时缩放图像。请查看此来源: 链接到示例

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100006747

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档