2016-10-28 123 views
5

我有一個HTML頁面iframe其內容我需要滾動到加載時的某個位置。我的例子在除了iOS Safari之外的大多數瀏覽器中都能正常工作 - 這是我真正需要的。它傾向於在第一頁加載時在iOS Safari中運行,但通常在刷新之後會刷新頂部的iframe內容。iOS的Safari瀏覽器不滾動,以錨定在iframe

我讀過關於重定向導致#anchorname被刪除的問題,但這不是在這種情況下發生的情況。

真實iframe內容和主頁面在不同的域。我可以影響iframe的內容,但我無法控制它。它也被用於其他目的,所以我有限的能力做任何可能會干擾的自定義。

住在這裏的鏈接: https://s3.amazonaws.com/ios-iframe-test/iframe_test.html

這裏是父內容:

<!DOCTYPE html> 
<html> 
    <head> 
    <title>test</title> 
    <meta content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=0" name="viewport"> 

    <style type="text/css"> 

     #root { 
     position: relative; 
     } 

     #wrapper { 
     height: 300px; 
     width: 300px; 
     overflow-x: hidden; 
     overflow-y: scroll; 
     position: relative; 
     -webkit-overflow-scrolling: touch; 
     } 

     iframe { 
     width: 100%; 
     height: 100%; 
     } 

    </style> 

    </head> 
    <body> 
    <h1>Why won't this iframe scroll to where I want?</h1> 
    <div id="root"> 
     <div id="wrapper"> 
     <iframe src="https://s3.amazonaws.com/ios-iframe-test/iframe_content.html#scrolltome"></iframe> 
     </div> 
    </div> 
    </body> 
</html> 

這裏是iframe內容:

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
</head> 

<body> 

    <h1>Have some ipsum...</h1> 
    <p> 
    Lorem... (live example has much more here just to make the scrolling apparent) 
    </p> 

    <h1 style="color: red;"> 
    <a name="scrolltome" id="scrolltome">This is where I want to scroll></a> 
    </h1> 

    <p> 
    Lorem... 
    </p> 

</html> 
+0

Safari在滾動iframe時存在很多問題。你可以使用JS解決方案嗎? –

回答

0

這是由於iOS的Safari瀏覽器的bug,從而iframe擴展到其內容的高度。您可以驗證這一點上使用Safari桌面調試器和運行:

document.querySelector('iframe').offsetHeight

的解決方案是通過將你的內容變成position: fixed容器中,並允許其滾動減少IFRAME體的高度。

例如,將正文的內容爲<main>標籤和設置樣式如下:

<html> 
    <head> 
     <style> 
      main { 
      position: fixed; 
      top: 0; 
      right: 0; 
      bottom: 0; 
      left: 0; 
      padding: 10px; 
      overflow-y: scroll; 
      -webkit-overflow-scrolling: touch; 
      z-index: 1; 
      } 
     </style> 
    </head> 
    <body> 
     <main> 
      <h1>Have some ipsum...</h1> 
      <p>Lorem... (live example has much more here just to make the scrolling apparent)</p> 
      <h1 style="color: red;"> 
      <a name="scrolltome" id="scrolltome">This is where I want to scroll</a> 
      </h1> 
      <p> 
      Lorem... 
      </p> 
     </main> 
    </body> 
    </html> 

這告訴Safari瀏覽器內嵌框架體是相同的高度,包含它的頁面,但其內容是可滾動的。你的錨點現在可以工作。

相關問題