开发者

Firefox reloading parent page in iframe when clicking named anchor

开发者 https://www.devze.com 2022-12-26 05:03 出处:网络
My site has an iframe which is dynamically populated with html content. The html often contains named anchors, which 开发者_JAVA百科work fine in IE/Chrome but in Firefox it reopens the entire page wit

My site has an iframe which is dynamically populated with html content. The html often contains named anchors, which 开发者_JAVA百科work fine in IE/Chrome but in Firefox it reopens the entire page within the iframe.

Here's an example: load the page in firefox, scroll to the bottom of the iframe, click the "back to top" link, and you will see what I am talking about.

<html><head></head><body onload="setFrameContent();"><script>

var htmlBody = '<html> <head></head> <body>' +
'<a name="top"><h1>top</h1></a>' +
'<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>' +
'<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>' +
'<a href="#top">back to top</a></body> </html> ';

function setFrameContent(){
    if (frames.length > 0) {
        var d = frames[0].document;
        d.open();
        d.write(htmlBody);
        d.close();
    }
}

</script>
<h1>Here's an iframe:</h1>
<iframe id="htmlIframe" style="height: 400px; width: 100%"><p>Your browser does not support iframes.</p></iframe>
</body></html>

Any ideas?


I had the same problem and found this workaround.

<html>
<head>
<script>
var htmlBody = '<html> <head></head> <body>' +
'<a id="top"><h1>top</h1></a>' +
'<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>' +
'<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>' +
'<a href="javascript:parent.gotoAnchor(\'top\')">back to top</a></body> </html> ';

function setFrameContent(){
    if (frames.length > 0) {
        var d = frames[0].document;
        d.open();
        d.write(htmlBody);
        d.close();
    }
}

function gotoAnchor(id)
{
    var el = null;
    el = window.frames['myiframe'].document.getElementById(id);
    window.frames['myiframe'].scrollTo(0,el.offsetTop);
}
</script>
</head>
<body onload="setFrameContent();">
<h1>Here's an iframe:</h1>
<iframe name="myiframe" id="htmlIframe" style="height: 400px; width: 100%"><p>Your browser does not support iframes.</p></iframe>
</body>
</html>

Hope this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消