在Chrome中防止iframe的location.hash滚动父窗口

9

情景:

我正在构建一个在Chrome中运行的信息亭应用程序。我通过使用带有锚点的链接(http:/www.whatever.com/#specific_content)将来自另一个域的iframe加载到模态框中。

问题:

当该内容加载时,iframe会跳转到#specific_content,但父页面也会跳转。

这是一个单页信息亭应用程序,因此父页面的位置非常重要。 实际场景的细节比上面的描述要复杂一些:

  1. 为了防止应用程序滚动,我使用body {overflow:hidden;}。
  2. 为了允许定位,我使用一个设置为视口大小的包装容器。
  3. 为了模拟滚动,我要么绝对重新定位包装器,要么绝对定位包装器内的内容。

为了演示问题,我设置了一个jsFiddle,但您需要在没有jsFiddle chrome的情况下查看输出,以了解问题的全部范围:

步骤1)单击“链接到内容”,这将重新定位包装器

步骤2)单击“链接到加载”,这将加载iFrame内容

演示:http://jsfiddle.net/w47GT/8/embedded/result/

Fiddle: 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'
        });
    });
});

干得好,@DJDavid98。 - natepers
2个回答

5
答案可以在这里找到:使用指定的#element加载iframe会将父视图点移动到相同位置 解决方案: 在完全加载iFrame之前隐藏它,这将绕过影响父页面的锚点效果。
演示:http://jsfiddle.net/w47GT/12/embedded/result/ JSFiddle: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 指出这个答案。

非常优秀的回答!这个方法帮助我解决了一个非常烦人的bug,就是动态加载twilio的呼叫录音iframe会使界面跳动。谢谢! - dmulvi

-1
我在这里有点盲目,但您是否尝试过将类似于此附加到外部页面的DOM?
$(window).on("hashchange", function(e) {
  e.preventDefault();
});

真遗憾,很抱歉我不能提供更多帮助。 - Moby's Stunt Double

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