javascript 跳转到 iframe 中的锚点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13893256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:05:02  来源:igfitidea点击:

Jumping to anchor in iframe

javascripthtmlscroll

提问by Karl Heinz

Situation:

情况:

First: iframewith id miframe, displaying a site with the anchor called suchen, i.e.

第一:iframeid miframe,显示一个带有名为suchen的锚点的站点,即

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

Second. Parent frame.

第二。父框架。

Goal: Make a link within the parent frame looking like

目标:使父框架内的链接看起来像

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

make the content in the iframebe scrolled to the anchor suchen. My approach.

使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);works in so far, that scroll happens to 200. But I need scrolling to the very anchor, wherever it is in the iframe. Ideas?

childWindow.scrollTo(0,200);到目前为止,该滚动发生在 200。但我需要滚动到非常锚点,无论它在iframe 中的任何位置。想法?

回答by Alvin Wong

Normally you would use a link like <a href="#your_anchor_name_or_id">Go to the anchor</a>. If you want to do this using JavaScript, you can change the value of window.location.hash. The following code should do that within a frame:

通常你会使用像<a href="#your_anchor_name_or_id">Go to the anchor</a>. 如果您想使用 JavaScript 执行此操作,您可以更改window.location.hash. 以下代码应在一个框架内执行此操作:

document.getElementById("the_id_of_your_iframe").contentWindow.location.hash = "your_anchor_name_or_id";

If you don't want to change the hash value, there is an example on MDN. You can modify it for an iframe.

如果您不想更改哈希值,则MDN 上一个示例。您可以为 iframe 修改它。

回答by extramaster

The following code should scroll the iframe to the anchor's position:

以下代码应将 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/

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