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

场景:

我正在构建一个在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://sofzh.miximages.com/javascript/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

   

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指出这个答案。

我在这里的黑暗中拍摄了一下,但你是否尝试过这样的东西附在外页的DOM上?

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