我在 <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
(显然,您可以选择任何所需的值)。< 链接包含三个属性,每个属性支持两种滚动到框架中链接的方法:
target="target-iframe"
和href="test.html#activate"
这是回退方法,以防出现错误或用户禁用了 JavaScript。
链接的目标是框架,href
属性必须是框架的路径,以 anchor 为后缀,例如测试.hrml#activate
。此方法将导致框架页面重新加载。此外,如果 anchor 已经位于#activate
,则此方法将不再有效。- 这是绝妙的解决方案,不会失败。所需的框架通过全局
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/