通过在Chrome中滚动父窗口来阻止iframe中的location.hash

nat*_*ers 9 javascript css browser jquery google-chrome

场景:

我正在构建一个在Chrome中运行的自助服务终端应用.在其中我通过带锚的链接(http:/www.whatever.com/#specific_content)将来自另一个域的iframe加载到模态中.

问题:

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

这是一个单页自助服务终端应用程序,因此父页面的位置非常重要.场景的实际细节比上面的更复杂:

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

为了演示这个问题,我设置了一个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; }
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

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'
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

nat*_*ers 5

可以在此处找到答案:使用指定的#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();
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

感谢@ DJdavid98指出这个答案.