How can I target a div inside an iframe?

旧时模样 提交于 2020-01-12 05:33:07

问题


I have an element inside an <iframe> I'd like to activate using a link outside the <iframe>.

Example:

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

I thought this would work but obviously does nothing because I'm stupid. Any ideas?


回答1:


Framed page (test.html):

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

Page containing the 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

Explanation

  • The frame has a name attrbute with the value of target-iframe (obviously, you can choose any desired value).
  • The link contains three attributes, each supporting two methods to scroll to a link in the frame:

    1. target="target-iframe" and href="test.html#activate"
      This is the fallback method, in case of an error occurs, or if the user has disabled JavaScript.
      The target of the link is the frame, the href attribute must be the path of the frame, postfixed by the anchor, eg test.hrml#activate. This method will cause the framed page to reload. Also, if the anchor is already at #activate, this method will not work any more.
    2. This is the elegant solution, which shold not fail. The desired frame is accessed through the global frames object (by name, NOT by id, target-iframe). Then, the anchor is selected (document.getElementById('activate').
      Finally, the scrollIntoView method is used to move the element inside the viewport.
      The onclick method ends with return false, so that the default behaviour (ie following the link, causing a page refresh), does not happen.

Your current code did not work, because of the missing name attribute (target="..." cannot match IDs, only names). Also, #activate is parsed in the context of the current page, so, the link points to page-containing-frame.html.



来源:https://stackoverflow.com/questions/8501595/how-can-i-target-a-div-inside-an-iframe

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!