用js实现页面中的图片点击放大特效,无需更改页面源码标签

2023-08-20 建站知识 浏览 手机预览
文章来源:http://www.imtr.cn/html/n265.html

用js实现页面中的图片点击放大特效,无需更改页面源码标签

首选添加css代码

<style type="text/css">
/* 滑块样式 */
body::-webkit-scrollbar {
width: 0px;  /* 滑块宽度 */ 
}
body::-webkit-scrollbar-thumb {  
border-radius: 10px;   /* 滑块圆角 */ 
background-color:rgba(47, 54, 64, 0); /* 滑块颜色 默认透明 */ 
}
body:hover::-webkit-scrollbar-thumb {  
border-radius: 10px;   /* 滑块圆角 */
background-color:#000000; /* 滑块颜色 划过时改变颜色 */ 
}
/* 遮罩层样式 */
#overlay {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.8); /* 半透明黑色背景 */
z-index: 9999; /* 确保遮罩层位于最上层 */
}
#enlarged-image-container {
text-align: center;
position: absolute;
width: 100%;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
#enlarged-image {
max-width: 96%; /* 控制图片最大宽度 */
max-height: 85vh; /* 控制图片最大高度 */
display: block;
margin: auto;
}
#button {
height: 30px;
color: #ffffff;
border-width: 0px;
background-color: #e74c3c;
box-shadow: 0px 5px 0px 0px #af1000;
}
</style>

将以下代码添加到页面底部,</body>代码之前

<!-- 点击放大图片 -->
<div id="overlay" style="display: none;">
  <div id="enlarged-image-container">
    <img id="enlarged-image" src="">
    <button id="button">关闭预览</button>
  </div>
</div>
<script>
document.addEventListener("click", function(event) {
  if (event.target.tagName === "IMG") {
    const imgSrc = event.target.src;
    const enlargedImage = document.getElementById("enlarged-image");
    enlargedImage.src = imgSrc;		
    document.body.style.overflow = "hidden";// 禁止页面滚动

    //获取图片宽度并设置给“关闭”按钮
    document.getElementById("overlay").style.display = "block";
    const imgWidth = enlargedImage.width;
    const closeButton = document.getElementById("button");
    closeButton.style.width = imgWidth + "px";
    //获取图片宽度并设置给“关闭”按钮 end
  }
});

// 点击遮罩层时,隐藏遮罩层
document.getElementById("overlay").addEventListener("click", function(event) {
  if (event.target.id === "overlay") {
    this.style.display = "none";
    document.body.style.overflow = "auto";// 还原页面滚动
  }
});

// 点击按钮时,隐藏遮罩层
document.getElementById("button").addEventListener("click", function(event) {
  event.stopPropagation();
  document.getElementById("overlay").style.display = "none";
  document.body.style.overflow = "auto";// 还原页面滚动
});
</script>
<!-- 点击放大图片 end -->


原文地址:http://www.imtr.cn/html/n265.html
  • 如果你的问题还没有解决,可以点击页面右侧的“ ”,站长收到问题后会尽快回复解决方案到你的邮箱。
  • 创造始于问题,有了问题才会思考,有了思考,才有解决问题的方法,才有找到独立思路的可能。 —— 陶行知