iOS Safari无法滚动到iframe中锚定

时间:2016-10-28 15:03:09

标签: html ios iframe mobile-safari

我有一个HTML页面,其中iframe的内容需要在加载时滚动到某个位置。我的示例在除iOS Safari之外的大多数浏览器中都能正常工作 - 这是我真正需要的。它往往在第一页加载时在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>

1 个答案:

答案 0 :(得分:2)

这是由于iOS Safari错误导致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 iframe主体与包含它的页面的高度相同,但其内容是可滚动的。您的锚点现在可以正常工作。

相关问题