JS 图片局部放大

前提:感谢松妹,感谢松妹,感谢松妹

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style type="text/css">
    .small {
      width: 300px;
      height: 300px;
      background-image: url(./index.png);
      background-size: cover;
      border: 10px solid pink;
      float: left;
      position: relative;
    }
    .magnifier {
      width: 200px;
      height: 200px;
      position: absolute;
      top: 0;
      left: 0;
      background-color: yellow;
      opacity: 0.5;
      display: none;
    }
    .big {
      width: 450px;
      height: 450px;
      border: 10px solid pink;
      float: left;
      position: relative;
      overflow: hidden;
      display: none;
    }
    .big > img {
      position: absolute;
      width: 675px;
      height: 675px;
    }
  </style>
</head>
<body>
  <div class="small" id="small">
    <div class="magnifier" id="magnifier"></div>
  </div>
  <div class="big" id="big">
    <img src="./index.png" id="img">
  </div>
</body>

<script type="text/javascript">
  let smallBox = document.getElementById('small');
  let magnifier = document.getElementById('magnifier');
  let bigImg = document.getElementById('img');
  let bigBox = document.getElementById('big');

  smallBox.onmouseenter = function () { // 鼠标移入,显示放大镜和大图
    bigBox.style.display = 'block';
    magnifier.style.display = 'block';
  }

  smallBox.onmouseleave = function () { // 鼠标移出,隐藏放大镜和大图
    bigBox.style.display = 'none';
    magnifier.style.display = 'none';
  }

  smallBox.onmousemove = function (e) { // 放大镜移动事件
    let left = e.clientX - 100;
    let top = e.clientY - 100;
    if (left <= 0) left = 0;
    else if (left >= 100) left = 100;
    if (top <= 0) top = 0;
    else if (top >= 100) top = 100;
    magnifier.style.left = left + 'px';
    magnifier.style.top = top + 'px';
    moveBigBox(left, top);
  };

  function moveBigBox (left, top) { // 移动右边图片
    bigImg.style.left = `-${left * 2.25}px`; // (大盒子 / 小盒子) * (小盒子 / 放大镜)
    bigImg.style.top = `-${top * 2.25}px`;
  }
</script>
</html>

 

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值