如何通过JavaScript模拟iframe中的锚点击?

时间:2009-06-30 04:11:34

标签: javascript

我有一个显示报告的iframe窗口。要访问此iframe,我在父窗口上有一个展开/折叠按钮。

在iframe报告窗口中,我在报告底部有一个#PAGETOP锚点,即:

<tr><td style="padding-left:45px" class="bottom" colspan="99"><div id="ptAnchor"><a href="#PAGETOP"><img src="first.png" border="1" alt="Top of Page" /></a></div></td></tr>

当用户从父窗口按下“展开”按钮时,如何以编程方式模拟此#PAGETOP锚点的onclick?

3 个答案:

答案 0 :(得分:1)

使用#PAGETOP锚点是将窗口滚动到顶部。您可以编写一个函数来将窗口滚动到0,0坐标。

function ScrollToTop() {
    window.scroll(0, 0);
}

将此函数放入IFrame,并从父窗口调用它。

答案 1 :(得分:1)

在父文档中:

<a id="scrollToTop">Expand</a>
<script type="text/javascript">

   document.getElementById("scrollToTop").onclick = function(e) { 
      var childWindow =  document.getElementById("theIFrame").contentWindow;

      // this should emulate a click on the ptAnchor DIV's child A HREF.
      childWindow.document.getElementById("ptAnchor").firstChild.click();

      // alternatively, this will simply scroll the child window to the top-left corner
      childWindow.scrollTo(0,0);
   }
</script>
<iframe id="theIFrame" src="someDocOnTheSameDomain.html"></iframe>

您的iframe必须位于浏览器的同一域中,才允许在父框架和子框架之间编写脚本。

contentWindow 属性允许您访问子iframe的窗口对象。从那里,您可以编写Javascript来模拟点击或只是滚动窗口。

答案 2 :(得分:0)

您可以这样做:

<iframe name="foo"></iframe>
<button>Expand</button>

<script type="text/javascript">
  $(function(){
    $('button').click(function(){
      window.frames['foo'].location.hash = "top";
    });
  });
</script>