JavaScript实现图片放大预览效果

编程学习 2021-07-04 14:07www.dzhlxh.cn编程入门
这篇文章主要介绍了JavaScript实现图片放大预览效果,帮助大家更好的理解和制作JavaScript特效,感兴趣的朋友可以了解下

代码实现:

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

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .preview-img {
      position: relative;
      height: 398px;
    }
    
    .mask {
      display: none;
      position: absolute;
      top: 0;
      left: 0;
      width: 300px;
      height: 300px;
      background-color: skyblue;
      opacity: .4;
      border: 1px solid #ccc;
      cursor: move;
    }
    
    .big {
      overflow: hidden;
      display: none;
      position: absolute;
      top: 0;
      left: 410px;
      width: 500px;
      height: 500px;
      background-color: pink;
      z-index: 99;
      border: 1px solid #ccc;
    }
    
    .big img {
      position: absolute;
      top: 0;
      left: 0;
    }
  </style>
</head>

<body>
  <script>
    window.addEventListener('load', function() {
      var preview_img = document.querySelector('.preview-img');
      var mask = document.querySelector('.mask');
      var big = document.querySelector('.big');
      // 显示与隐藏
      preview_img.addEventListener('mouseover', function() {
        mask.style.display = 'block';
        big.style.display = 'block';
      });
      preview_img.addEventListener('mouseout', function() {
        mask.style.display = 'none';
        big.style.display = 'none';
      });
      // 盒子跟随鼠标移动
      preview_img.addEventListener('mousemove', function(e) {
        var x = e.pageX - this.offsetLeft;
        var y = e.pageY - this.offsetTop;
        var maskX = x - mask.offsetWidth / 2;
        var maskY = y - mask.offsetHeight / 2;
        var maskMax = preview_img.offsetHeight - mask.offsetHeight;
        if (maskX <= 0) {
          maskX = 0;
        } else if (maskX >= maskMax) {
          maskX = maskMax;
        }
        if (maskY <= 0) {
          maskY = 0;
        } else if (maskY >= maskMax) {
          maskY = maskMax;
        }
        mask.style.left = maskX + 'px';
        mask.style.top = maskY + 'px';

        // 大图,根据比例计算坐标
        var bigImg = document.querySelector('.bigImg');
        var bigMax = bigImg.offsetWidth - big.offsetWidth;
        var bigX = bigMax * maskX / maskMax;
        var bigY = bigMax * maskY / maskMax;
        bigImg.style.left = -bigX + 'px';
        bigImg.style.top = -bigY + 'px';
      });
    });
  </script>
  <div class="preview-img">
    <img src="https://s1.ax1x.com/2020/10/12/027yRg.jpg" alt="">
    <div class="mask"></div>
    <div class="big">
      <img src="https://s1.ax1x.com/2020/10/12/0276zQ.jpg" alt="" class="bigImg">
    </div>
  </div>
</body>

</html>

实现效果:

以上就是JavaScript实现图片放大预览效果的详细内容,更多关于JavaScript 图片放大的资料请关注狼蚁SEO其它相关文章!

Copyright © 2016-2025 www.dzhlxh.cn 金源码 版权所有 Power by

网站模板下载|网络推广|微博营销|seo优化|视频营销|网络营销|微信营销|网站建设|织梦模板|小程序模板