如何使用<iframe></iframe>标签

240 阅读1分钟

iframe 标签使用

作用

可以在一个页面中显示来自另一个 URL 的内容,例如整合第三方服务、广告、地图、视频播放器等等。

基本语法

<iframe src="URL" width="宽度" height="高度" frameborder="边框宽度" scrolling="滚动条状态" allow="允许的特性"></iframe>

属性

name:定义框架的名称

width:设置框架显示的宽度

height:设置框架显示的高度

src:设置框架的地址,可以是页面地址,也可以是图片地址

scrolling:设置框架是否需要滚动条,取值可以是yes、no、auto

frameborder:定义是否需要显示边框,取值为1表示需要边框,0表示不需要边框 align:设置元素对齐方式,取值可以是left,right,top,middle,bottom

allow:指定要启用的特性,例如音频、视频播放、运动传感器等。例如 allow="autoplay; encrypted-media"

sandbox:限制内联框架中的内容可以做什么,提高安全性。它可以接受多个空格分隔的值,如 "allow-scripts""allow-same-origin" 等。

loading:指定加载策略,可以是 "eager"(立即加载)或 "lazy"(延迟加载)。

配合a标签或NuxtLink标签使用

//跳转其他页面且携带参数
<template>
    <NuxtLink :to="/look?id=1" target="_blank" rel="noopener"> 跳转</NuxtLink>
</template>
​
//look页面
<script setup lang="ts">
    const { id } = useRoute().query;
</script>
​
<template>
    <iframe :src="'/api/getData?groupId=' + id " frameborder="0" width="100%" height="100%"></iframe>
</template>
​
/************************************************************/
<template>
    //@click.prevent阻止了<a>标签的默认行为,这样就不会触发页面跳转。
    <a @click.prevent="loadIframe">加载 Iframe</a> 
        <iframe ref="myIframe" frameborder="0" width="100%" height="100%"></iframe>
</template>
​
<script setup lang="ts">
const myIframe = ref(null);
function loadIframe() {
  myIframe.value.src = 'https://example.com';
}
onMounted(() => {
  myIframe.value.src = ''; // 初始化时清空src,防止预加载
});
</script>