You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现图片显示真实尺寸或屏幕50%大小而非全屏?

实现图片点击放大至真实尺寸或屏幕50%大小

替换全屏API的方案是通过创建全屏遮罩层来展示放大后的图片,通过CSS限制图片最大尺寸为屏幕的50%,同时保留图片真实尺寸上限,点击缩略图触发放大,点击遮罩或图片关闭。

完整代码实现

HTML结构

<!-- 缩略图 -->
<img class="zoomE" src="{{ x }}" width="120" height="90" />

<!-- 放大遮罩容器 -->
<div id="imageZoomOverlay">
  <img id="zoomedImage" />
</div>

CSS样式

#imageZoomOverlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.8);
  display: none;
  justify-content: center;
  align-items: center;
  cursor: zoom-out;
  z-index: 9999;
}

#zoomedImage {
  /* 最大不超过屏幕的50% */
  max-width: 50vw;
  max-height: 50vh;
  /* 同时不超过图片真实尺寸 */
  width: auto;
  height: auto;
}

JavaScript逻辑

window.onload = () => {
  const overlay = document.getElementById('imageZoomOverlay');
  const zoomedImg = document.getElementById('zoomedImage');
  const thumbnails = document.getElementsByClassName('zoomE');

  // 绑定缩略图点击事件
  for (const img of thumbnails) {
    img.addEventListener('click', (e) => {
      e.stopPropagation();
      zoomedImg.src = img.src;
      overlay.style.display = 'flex';
    });
  }

  // 点击遮罩层关闭放大
  overlay.addEventListener('click', () => {
    overlay.style.display = 'none';
  });

  // 点击放大图片也关闭
  zoomedImg.addEventListener('click', (e) => {
    e.stopPropagation();
    overlay.style.display = 'none';
  });
};

关键说明

  • 遮罩层使用fixed定位全屏覆盖,半透明背景突出放大的图片
  • max-width:50vw和max-height:50vh限制图片最大显示尺寸为屏幕的50%,width:auto/height:auto确保图片不会被拉伸,且不超过自身真实分辨率
  • 通过事件绑定实现交互逻辑,stopPropagation避免事件冒泡导致的误触发

内容的提问来源于stack exchange,提问作者pyrazs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 18:43:12