原生JS和CSS实现点击图片预览放大

效果:

在这里插入图片描述

代码实现,可以直接复制到本地测试(把图片路径换一下)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>3.图片预览</title>
  <style>
    .black_overlay {
     
     
      display: none;
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.7);
      z-index: 100;
    }

    .enlargeContainer {
     
     
      display: none;
    }

    .enlargePreviewImg {
     
     
      /*这里我设置的是:预览后放大的图片相对于整个页面定位*/
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      
      /*宽度设置为页面宽度的70%,高度自适应*/
      width: 70%;
      z-index: 200;
    }

	/*关闭预览*/
    .close {
     
     
      position: absolute;
      top: 20px;
      right: 20px;
      width: 20px;
      height: 20px;
      cursor: pointer;
      z-index: 200;
    }
  </style>
</head>
<body>

<!--测试图片-->
<img src="./images/maying.jpg" id="toEnlargeImg">

<!--黑色遮罩-->
<div class="black_overlay" id="black_overlay"></div>

<!--预览容器,存放点击放大后的图片-->
<div class="enlargeContainer" id="enlargeContainer">
  <!-- 关闭按钮,一个叉号图片 -->
  <img src="./images/close.png" class="close" id="close">
</div>

<script>
  let black_overlay = document.getElementById('black_overlay');
  let enlargeContainer = document.getElementById('enlargeContainer');
  let closeBtn = document.getElementById('close');

  let toEnlargeImg = document.getElementById('toEnlargeImg');
  toEnlargeImg.addEventListener('click', function () {
     
     
    // 获取当前图片的路径
    let imgUrl = this.src;
    // 显示黑色遮罩和预览容器
    black_overlay.style.display = 'block';
    enlargeContainer.style.display = 'block';
    let img = new Image();
    img.src = imgUrl;
    img.classList.add('enlargePreviewImg');
    if (closeBtn.nextElementSibling) {
     
     
      enlargeContainer.removeChild(closeBtn.nextElementSibling);
    }
    enlargeContainer.appendChild(img);
  });

  // 关闭预览
  closeBtn.addEventListener('click', function () {
     
     
    black_overlay.style.display = 'none';
    enlargeContainer.style.display = 'none';
  });
</script>

</body>
</html>

前端学习交流QQ群:862748629 点击加入

猜你喜欢

转载自blog.csdn.net/weixin_43974265/article/details/116501672