如何在iframe中定位div?

Sat*_*iva 7 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>
Run Code Online (Sandbox Code Playgroud)

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

Rob*_*b W 14

加框页面(test.html):

....... lots of content .... 
<div id="activate">Inside frame</div>
Run Code Online (Sandbox Code Playgroud)

包含frame(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
Run Code Online (Sandbox Code Playgroud)

说明

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

    1. target="target-iframe"并且href="test.html#activate"
      这是回退方法,在发生错误的情况下发生时,或如果用户已经停用了JavaScript.
      链接的目标是帧,href属性必须是帧的路径,后缀为锚点,例如test.hrml#activate.此方法将导致框架页面重新加载.此外,如果锚已经存在#activate,则此方法将不再起作用.
    2. 这是优雅的解决方案,不会失败.通过全局frames对象(按名称,不按ID target-iframe)访问所需的帧.然后,锚被选中(document.getElementById('activate').
      最后,该 scrollIntoView方法用于移动视窗内的元素.
      onclick方法与结束return false,使默认行为(即下面的链接,导致页面刷新),不会发生.

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

  • 人类知道的最大回应,谢谢你的一切! (2认同)