在iframe中跳转到锚点

5

情境:

首先,有一个id为miframeiframe,展示一个带有锚点suchen的网站,即:

<div id="suchen"></div>. 

第二步。父框架。

目标:在父框架内创建一个看起来像这样的链接

<a class="LINK0" title="" href="javascript:springen('suchen');">w/e</a> 

使iframe中的内容滚动到锚点suchen。我的方法是:
function springen(anker) { 
    var childWindow =  document.getElementById("miframe").contentWindow;

    // this should emulate a click on the ptAnchor DIV's child A HREF.
    //childWindow.document.getElementById(anker).firstChild.click();
    //childWindow.document.getElementById(anker).scrollIntoView();
    // alternatively, this will simply scroll the child window to the top-left corner
    //childWindow.scrollTo(0,200);
}

childWindow.scrollTo(0,200); 可以实现滚动到200像素的位置。 但我需要滚动到iframe中任何位置的标记处。有什么想法吗?

2个回答

12
通常情况下,您会使用类似于 <a href="#your_anchor_name_or_id">转到锚点</a> 的链接。如果您想使用JavaScript完成此操作,可以更改window.location.hash的值。以下代码应该在框架内实现此操作:
document.getElementById("the_id_of_your_iframe").contentWindow.location.hash = "your_anchor_name_or_id";

如果您不想更改哈希值,可以参考MDN上的示例。您可以为iframe进行修改。

我遇到了这个错误: 在Firefox 91.6.0esr上,未捕获的DOM异常:被禁止访问跨域对象上的“hash”属性。 - Mattman85208

4
以下代码应该将iframe滚动到锚点的位置:
function springen(anker) { 
    var childWindow =  document.getElementById("miframe").contentWindow;
    childWindow.scrollTo(0,childWindow.document.getElementById('suchen').offsetTop);
}

Edit:

JSFiddle: http://jsfiddle.net/pkvhw/6/


不尝试的话...但是我在想你应该循环遍历它的所有offsetParent,并累加它们的offsetTop - Alvin Wong

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接