JS实现放大镜效果
更新:HHH   时间:2023-1-7


<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
  <style>
    .img {
      width: 300px;
      height: 400px;
      position: relative;
    }

    .img img {
      width: 100%;
      height: 100%;
    }

    .mask {
      width: 200px;
      height: 200px;
      position: absolute;
      left: 0;
      top: 0;
      background-color: yellow;
      opacity: 0.3;
      display: none;
      cursor: move;
    }

    .big {
      width: 400px;
      height: 400px;
      position: absolute;
      left: 300px;
      top: 0;
      overflow: hidden;
      display: none;
    }

    .big img {
      width: 150%;
      height: 200%;
      position: absolute;
      left: 0;
      top: 0;
    }
  </style>
  <title>Document</title>
</head>

<body>
  <div class="img">
    <img src="./8131572850838_.pic.jpg" alt="">
    <div class="mask"></div>
    <div class="big">
      <img src="./8131572850838_.pic.jpg" alt="">
    </div>
  </div>

  <script>
    $(function () {
      var imgBox = $('.img')
      var mask = $('.mask')
      var big = $('.big')

      imgBox.on({
        mouseover: function (e) {
          mask.css({ 'display': 'block' })
          big.css({ 'display': 'block' })

        },
        mouseout: function (e) {
          mask.css({ 'display': 'none' })
          big.css({ 'display': 'none' })
        },
        mousemove: function (e) {

          // 鼠标在盒子中的位置
          var x = e.pageX - imgBox.offset().left
          var y = e.pageY - imgBox.offset().top

          // 遮挡层的坐标
          var maskX = x - mask.width() / 2
          var maskY = y - mask.height() / 2

          // 遮挡层最大移动距离
          var maxX = imgBox.width() - mask.width()
          var maxY = imgBox.height() - mask.height()

          if (maskX <= 0) {
            maskX = 0
          } else if (maskX > maxX) {
            maskX = maxX
          }
          if (maskY <= 0) {
            maskY = 0
          } else if (maskY > maxY) {
            maskY = maxY
          }
          mask.css({
            'left': maskX,
            'top': maskY
          })

          // 大图片的最大移动距离
          var bigImg = big.children('img')
          var bigMaxX = bigImg.width() - big.width()
          var bigMaxY = bigImg.height() - big.height()

          // 大图片移动距离   
          // mask最小移动距离 / mask最大移动距离 = big最小移动距离 / big最大移动距离
          var bigX = maskX * bigMaxX / maxX
          var bigY = maskY * bigMaxY / maxY

          // 相反方向移动需要  负号
          bigImg.css({
            'left': -bigX,
            'top': - bigY
          })

        }

      }) // imgBox.on

    })
  </script>
</body>

</html>
返回开发技术教程...