2013-04-08 73 views
8

场景:防止从的location.hash滚动父窗口在Chrome

我建立一个信息亭应用在Chrome中运行。在它中,我通过链接(http:/www.whatever.com/#specific_content)通过链接将另一个域中的iframe加载到模式中。

问题:

如果这些内容的负载,在iframe跳下来的#specific_content但父页面还跳跃。

这是一个单页信息亭应用程序,所以父页面的位置非常重要。 场景的实际细节不仅仅是上面有点复杂:

  1. 为了抑制滚动的应用程序我有身体{溢出:隐藏;}
  2. 为了能够定位我使用的包装容器设置为视口的大小。
  3. 要模拟滚动,我要么绝对重新定位包装,要么绝对地在包装中定位内容。

为了证明我已经设置了的jsfiddle问题,但需要看到的输出没有的jsfiddle铬看到问题的全部范围:

步骤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' 
     }); 
    }); 
}); 
+2

http://stackoverflow.com/questions/14465378/loading-iframe-with-an-element-specified-moves-the-parent-viewpoint-to-the-same – SeinopSys 2013-04-08 16:01:18

+0

那么,好吧,@ DJDavid98很好地完成。 – natepers 2013-04-08 17:56:25

回答

4

答案可以在这里找到:Loading iframe with an #element specified moves the parent viewpoint to the same location

解决方案:

隐藏的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用于指向这个答案。

+0

优秀的答案!这种方法帮助我修复了一个非常恼人的错误,即动态加载iframe以播放来自twilio的通话记录会使接口向下跳。谢谢! – 2013-08-05 16:40:49

-1

我小号在黑暗中一点点在这里,但你有没有尝试过这样的东西附加到外部页面的DOM?

$(window).on("hashchange", function(e) { 
    e.preventDefault(); 
}); 
+0

我尝试过但没有快乐:http://jsfiddle.net/w47GT/10/embedded/result/ – natepers 2013-04-08 17:30:51

+0

该死的。抱歉,我无法提供更多帮助。 – 2013-04-08 17:35:35