Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
482 views
in Technique[技术] by (71.8m points)

javascript - Jumping to anchor in iframe

Situation:

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

<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 iframe be scrolled to the anchor suchen. My approach.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...