如何将 HTML 嵌入到 HTML 中(并自动调整大小)?

问题描述 投票:0回答:1

如何将 HTML 嵌入到 HTML 中(并自动调整大小)?

我尝试使用 Inline Frame 元素(iframe) 标签;但由于默认的高度和宽度设置,iframe 仍保持默认大小。此外,我尝试操作 object-fit 属性;但 iframe 仍然保持相同的默认大小。

我知道我可以手动设置高度和宽度属性;但我喜欢其他 HTML 元素自动调整大小的方式,并且希望我的 iframe 能够“插入 HTML;但随后会避开并像其他 HTML 一样运行”,也就是说,使示例 2 看起来像示例 1,请参见屏幕截图。

注意:我不需要使用 iframe;但我尝试使用 iframe,因为 HTML Tag W3 Schools 页面建议这样做。

作为参考,我提供了两个 index.html 和 note.html 本地文件以及屏幕截图。

  1. index.html

    <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style type="text/css"> table, th, td { border: 1px solid black; text-align: left; } </style> <title>iframe experiment</title> </head> <body> <h3>Example 1: Duplicated note</h3> <p>In the following example I duplicate my note 3 times. Notice how the HTML sizes as expected.</p> <p>Consider the following note:</p> <p>Note: This is a note.</p> <p>Consider the same note in a list:</p> <ol> <li><p>Note: This is a note.</p></li> </ol> <p>Consider the same note in a table:</p> <table> <tr> <th>Notes</th> </tr> <tr> <td><p>Note: This is a note.</p></td> </tr> </table> <h3>Example 2: Inline frame note</h3> <p>In the following example I embed my note 3 times with the <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe"><em>Inline Frame element (iframe)</em></a>. Notice how the inline frame looks wonky because of the default height and width.</p> <p>Consider the following note:</p> <iframe src="note.html"></iframe> <p>Consider the same note in a list:</p> <ol> <li><iframe src="note.html"></iframe></li> </ol> <p>Consider the same note in a table:</p> <table> <tr> <th>Notes</th> </tr> <tr> <td><iframe src="note.html" style="object-fit:none;"></iframe></td> </tr> </table> </body> </html>
    
    
  2. note.html

    <p>Note: This is a note.</p>
    
    
  3. 截图

html css iframe
1个回答
0
投票
两种选择。

HTML 文档 1 中的

iframe

允许您仅使用其 URL 来包含 HTML 文档 2,但

iframe
的大小由文档 1 而不是文档 2 决定。您可以使用 Javascript 技巧来解决此问题评论中由 @SteffenAndreasKloster 链接的文章。
另一种方法是在文档 1 中编写一些 Javascript,以 

fetch

将文档 2 的内容作为字符串,然后使用 insertAdjacentHTML() 将其插入到文档 1 中。这有效地将文档 2 合并到文档 1 中,因此“就像其他 HTML 一样”。

© www.soinside.com 2019 - 2024. All rights reserved.