HTML Iframe

HTML的<iframe>标签用于在一个网页中嵌入另一个网页。它也称为内联框架。例如,

<iframe src="https://programiz.pro" title="programiz pro website" height="500" width="500" ></iframe>

浏览器输出

Programiz.pro websize loaded inside an iframe

这里,

  • src: 用于指定要加载的网站的URL。
  • title: 包含一个title属性是一个好习惯,这样屏幕阅读器就可以为用户朗读标题。

<iframe> 的其他属性

<iframe> 有一些重要的属性。它们是

  • height and width
  • name
  • srcdoc

我们将详细探讨每一个。


height and width

我们可以使用heightwidth属性来设置<iframe>元素的高度和宽度。例如,

<iframe src="https://programiz.pro" height="200" width="300"></iframe>

我们也可以使用CSS通过style属性来设置<iframe>的宽度和高度。例如,

<iframe src="https://programiz.pro" style="height:200px;width:300px"></iframe>

为 iframe 分配页面空间时,添加高度和宽度很重要。它可以防止 iframe 加载时内容发生移动。


name

name属性用于为 iframe 指定名称。它可以用作其他HTML元素(如<a>标签)的目标。例如,

<iframe src="https://parewalabs.com" name="iframe_target" height="500" width="400"></iframe>

<a href="https://www.programiz.pro" target="iframe_target">Switch to Programiz Pro</a>

浏览器输出(点击链接之前)

A website open on an iframe with an anchor which targets the iframe

浏览器输出(点击链接之后)

A website open on an iframe with an anchor which targets the iframe

在这里,点击<a>标签会更改目标窗口的URL,而不是当前窗口。


srcdoc

我们可以直接向 iframe 发送 HTML,而不是网站 URL,它将代替另一个网站显示。例如,

<iframe srcdoc="<h1>Learn to code</h1>"></iframe>

浏览器输出

Srcdoc attribute used to render custom HTML inside an iframe

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战