初级JS--放大镜效果

css部分:

 * {
        margin: 0;
        padding: 0;
      }
      #normal {
        width: 400px;
        height: 400px;
        position: relative;
        border: 1px red solid;
      }
      #small {
        background: red;
      }
      #small img {
        width: 400px;
        height: 400px;
      }
      .big {
        position: absolute;
        height: 400px;
        width: 400px;
        left: 450px;
        top: 0;
        overflow: hidden;
        display: none;
        border: 1px red solid;
      }
      .big-img {
        position: absolute;
        left: 0;
        top: 0;
      }
      .box {
        width: 200px;
        height: 200px;
        background: rgba(255, 255, 0, 0.3);
        position: absolute;
        left: 0px;
        top: 0px;
        display: none;
      }

HTML部分:

  <div id="normal">
      <div id="small">
        <img src="../images/normal.jpg" alt="" />
        <div class="box"></div>
      </div>
      <div class="big">
        <img src="../images/big.jpg" alt="" class="big-img" />
      </div>
    </div>

JS部分:

const normal = document.querySelector("#normal");
      const box = document.querySelector(".box");
      const bigDiv = document.querySelector(".big");
      const bigImg = document.querySelector(".big-img");
      normal.onmouseenter = function () {
        box.style.display = "block";
        bigDiv.style.display = "block";

        let bigImgWidth =
          (bigDiv.offsetWidth * normal.offsetWidth) / box.offsetWidth;
      };
      normal.onmoouseleave = function () {
        box.style.display = "none";
        bigDiv.style.display = "none";
      };
      normal.onmousemove = function (evt) {
        let offsetX = evt.pageX - normal.offsetLeft;
        let offsetY = evt.pageY - normal.offsetTop;

        let boxX = offsetX - box.offsetWidth / 2;
        let boxY = offsetY - box.offsetHeight / 2;

        if (boxX <= 0) {
          boxX = 0;
        }
        if (boxY <= 0) {
          boxY = 0;
        }
        if (boxX >= normal.offsetWidth - box.offsetWidth) {
          boxX = normal.offsetWidth - box.offsetWidth;
        }
        if (boxY >= normal.offsetWidth - box.offsetWidth) {
          boxY = normal.offsetWidth - box.offsetWidth;
        }
        box.style.left = boxX + "px";
        box.style.top = boxY + "px";

        let bigImgX = (-boxX * bigImg.offsetWidth) / normal.offsetWidth;
        let bigImgY = (-boxY * bigImg.offsetHeight) / normal.offsetHeight;

        bigImg.style.left = bigImgX + "px";
        bigImg.style.top = bigImgY + "px";
      };

运行结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值