html - 如何定位 iframe 中的 div?

标签 html iframe

我在 <iframe> 中有一个元素我想使用 <iframe> 之外的链接激活.

例子:

<iframe src="iframe.html" id="iframe">
    *inside the iframe*  
    <div id="activate" class="activate">
</iframe>
<a href="#activate" target="iframe">Link</a>

我认为这会起作用,但显然什么也没做,因为我很愚蠢。有什么想法吗?

最佳答案

框架页面(test.html):

....... lots of content .... 
<div id="activate">Inside frame</div>

包含框架的页面(page-containing-frame.html):

<iframe src="test.html" name="target-iframe"></iframe>
<a href="test.html#activate"
       target="target-iframe"
       onclick="frames['target-iframe'].document.getElementById('activate')
                .scrollIntoView();return false">Click</a>
^ That's the link. I've split up code over multiple lines for visibility

解释

  • 框架有一个 name 属性,其值为 target-iframe(显然,您可以选择任何所需的值)。<
  • 链接包含三个属性,每个属性支持两种滚动到框架中链接的方法:

    1. target="target-iframe"href="test.html#activate"
      这是回退方法,以防出现错误或用户禁用了 JavaScript。
      链接的目标是框架,href属性必须是框架的路径,以 anchor 为后缀,例如测试.hrml#activate。此方法将导致框架页面重新加载。此外,如果 anchor 已经位于 #activate,则此方法将不再有效。
    2. 这是绝妙的解决方案,不会失败。所需的框架通过全局 frames 对象访问(按名称,而不是按 id,target-iframe)。然后,选择 anchor (document.getElementById('activate')
      最后,scrollIntoView方法用于在视口(viewport)内移动元素。
      onclick 方法以 return false 结束,因此不会发生默认行为(即跟随链接,导致页面刷新)。

您当前的代码无法运行,因为缺少 name 属性(target="..." 无法匹配 ID,只能匹配名称)。此外,#activate 在当前页面的上下文中被解析,因此,链接指向 page-containing-frame.html

关于html - 如何定位 iframe 中的 div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8501595/

相关文章:

html - 嵌套 <ul> 奇数/偶数 css

php - 分页显示用于分页的完整按钮

javascript - 圆 Angular <select> 下拉

javascript - Tabindex 不适用于 div 元素打开模式

html - 单击 F5(刷新)时不要更改 iframe 源

javascript - 将 Razor 数据插入 src 和 href 属性

jquery - 通过 ".content()"访问 iframe 内容没有成功

html - CSS:删除较大文本上的行高(前导)

javascript - 从 iframe 获取 div 值

iframe - 嵌入iframe的Youtube播放器上没有全屏按钮