使用iframe展示图片,如何设置图片的大小

使用iframe展示图片,如何设置图片的大小
前端:ant design vue1.6.2
说明:modal 框中套了一个iframe 用以展示附件,src接收的是后端传来的url,当附件为PDF或者视频时可以自动适应大小展示,但当附件为图片时,无法自动缩放,图片尺寸大的会有滚动条,而且图片他大,根本没法看
需求:图片可以自动缩放,没有滚动条
代码部分:

            <a-modal v-model="File_visible" id="FileModel" tabindex="-1" :dialog-style="{ top: '5px' }" :destroyOnClose=true
                width="118.5rem" :footer="null">
                <a-row class="rowStyle1">
                    <iframe class="my-iframe" id="mapFrame" ref="mapFrame" frameborder="0" scrolling="auto" :src="File_url"></iframe>
                </a-row>
            </a-modal>

样式部分:

.my-iframe {
  width: 100%;
  height: 100%;
  margin-left: auto;
  margin-right: auto;
}

.my-iframe img {
  max-width:118rem; 
  height: auto;  
}

您可以在 iframe 标签内使用 img 标签展示需要的图片,并设置其宽度和高度来控制图片的大小。例如:

<iframe src="example.html">
  <img src="example.jpg" width="500" height="300">
</iframe>

在上述代码中,我们向 iframe 中嵌入了一个 img 标签以展示 example.jpg 这张图片,并分别设置了它的宽度为 500px 和高度为 300px

也可以将 style 属性添加到 img 标签中,以便通过其他 CSS 属性来指定其宽度和高度,例如:

<iframe src="example.html">
  <img src="example.jpg" style="width: 500px; height: 300px;">
</iframe>

上述代码中,我们将 style 属性添加到 img 标签中,并通过 CSS 的 widthheight 属性来指定宽度和高度。

抱歉,我理解有误。针对你的使用场景,我们可以尝试使用JavaScript来动态设置iframe宽高来解决问题。首先需要确认嵌入的内容(图片、PDF、视频等)的类型,然后决定最终的显示方式。

以下是根据不同内容类型设置iframe大小的示例代码:

<a-modal v-model="File_visible" id="FileModel" tabindex="-1" :dialog-style="{ top: '5px' }" :destroyOnClose=true width="118.5rem" :footer="null">
  <a-row class="rowStyle1">
    <iframe class="my-iframe" id="mapFrame" ref="mapFrame" frameborder="0" scrolling="auto" :src="File_url" onload="resizeFrame()"></iframe>
  </a-row>
</a-modal>
function resizeFrame() {
  let iframe = document.getElementById("mapFrame");
  let content = iframe.contentDocument || iframe.contentWindow.document;

  // 判断嵌入内容的类型
  if (content.getElementsByTagName("img").length > 0) {
    // 嵌入的是图片,按照图片尺寸设置iframe大小
    let img = content.getElementsByTagName("img")[0];
    iframe.style.width = img.width + "px";
    iframe.style.height = img.height + "px";
  } else if (
    content.getElementsByTagName("embed").length > 0 ||
    content.getElementsByTagName("video").length > 0 ||
    content.getElementsByTagName("audio").length > 0
  ) {
    // 嵌入的是PDF、视频或音频,设置为100%宽度和高度
    iframe.style.width = "100%";
    iframe.style.height = "100%";
  } else {
    // 其他情况保持默认大小
    iframe.style.width = "118.5rem";
    iframe.style.height = "60rem";
  }
}

在这个示例中,我们使用了resizeFrame()函数来动态设置iframe大小。浏览器在加载iframe嵌入内容(图片、PDF、视频等)后会调用这个函数。首先,我们检查嵌入内容的类型。如果嵌入的是图片,我们可以根据图片的实际大小设置iframe大小。如果嵌入的是PDF、视频或音频,我们设置为100%宽度和高度来铺满整个iframe。对于其他情况,保持默认大小。

希望这个解决方案对你有帮助!