2013-04-08 74 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