场景:
我正在构建一个在 Chrome 中运行的信息亭应用程序。在其中,我通过带有锚点的链接将 iframe 从另一个域加载到模态中(http://www.whatever.com/#specic_content)。
问题:
当该内容加载时,iframe 会跳转到#specic_content,但父页面也会跳转。
这是一个单页面自助服务终端应用程序,因此父页面的位置非常重要。 该场景的实际细节比上面的要复杂一些:
为了演示这个问题,我设置了一个 jsFiddle,但是您需要在没有 jsFiddle chrome 的情况下查看输出才能看到问题的完整范围:
第 1 步)单击“链接到内容”,这将重新定位包装器
第2步)点击“链接加载”,这将加载iFrame内容
演示:http://jsfiddle.net/w47GT/8/embedded/result/
小提琴:http://jsfiddle.net/w47GT/8/
代码:
CSS:
html, body { height:100%; padding:0; margin: 0;overflow:hidden; }
.background {
width : 100%;
height:400%;
background:#333 url('http://incurablystircrazy.files.wordpress.com/2012/04/runner-at-sunset.jpg');
}
.wrapper { position:absolute;width:100%;height:200%; }
iframe { width:50%;height:50%;position:fixed;top:25%;left:50%;margin-left:-25%;border:2px solid red;background-color:#ddd; }
.link { width:100%;height:25px;position:absolute;top:25px;background-color:green; }
.anchor { position:absolute;top:400px;width:100%;height:25px;background-color:red; }
HTML
<div class="wrapper">
<div class="background"></div>
<a class="link" href="#linked">Link to content</a>
<a class="anchor" name="linked" href="http://www.smashingmagazine.com#footer" >Link to Load iFrame</a>
</div>
<iframe></iframe>
JS
$(function(){
$('.link').on('click',function(){ $('.wrapper').css({top:'-400px'}); });
$('.anchor').on('click',function(e){
e.preventDefault();
var href = $(this).prop('href');
$('iframe')
.attr({
src: href,
name: 'testing'
});
});
});
可以在这里找到答案:加载指定#element的iframe会将父视点移动到相同位置
解决方案:
隐藏 iFrame 直到其完全加载,这会绕过影响父页面的锚点。
演示:http://jsfiddle.net/w47GT/12/embedded/result/
小提琴:http://jsfiddle.net/w47GT/12/
JS
$(function(){
// Move the content wrapper up to simulate scroll
$('.link').on('click',function(){ $('.wrapper').css({top:'-400px'}); });
// Load iFrame content (previously hidden via CSS)
$('.anchor').on('click',function(e){
e.preventDefault();
var href = $(this).prop('href');
$('iframe')
.attr({
src: href,
name: 'testing'
}).on('load',function(){
$(this).show();
});
});
});
感谢@DJdavid98指出这个答案。
我想出了一种不太传统的方法,它肯定有一些缺点。
首先是缺点:在任何应用此解决方案的页面上,它都会阻止您有效地在网址中使用哈希来向下滚动到元素,并且
scrollIntoView
也会被阻止/受影响。如果您知道您的页面不需要执行这些操作,这对您来说可能是一个不错的选择。
scroll-padding-top
属性,该属性具有足够大的值,以便“填充”将滚动位置推回到页面的最顶部,从而防止散列滚动到任何地方。根据页面的设置方式,样式可以应用于文档的 html 标签,如下所示:
<style>
html {
scroll-padding-top: 99999px;
}
</style>
如果您知道 iframe 将在距页面顶部的距离内呈现,您也可以将其设置为较小的值,例如
200px
。
与公认的优秀答案相比,这种方法的一个优点是,在这种方法中,iframe 内容将滚动到哈希指向的任何位置,这可能是首先在 iframe URL 中使用哈希的目的。已接受的答案通过隐藏 iframe 以防止在父窗口上滚动的技巧具有跳过 iframe 内发生的滚动的副作用。
我在这里有点在黑暗中拍摄,但是你是否尝试过将类似的东西附加到外部页面的 DOM 上?
$(window).on("hashchange", function(e) {
e.preventDefault();
});