【问题标题】:how to make page scroll bottom and focus on iframe如何使页面滚动底部并专注于 iframe
【发布时间】:2019-08-19 21:49:50
【问题描述】:

我有一个网页,上面有一个带有一些内容的巨大横幅图像。在它下面,我有一个用于 youtube 视频的 iframe。该网页是响应式的,但是当我在移动设备上打开它时,标题太大,用户需要向下滚动才能查看视频。

我想要实现的是当用户在移动设备上打开网页时,它应该自动向下滚动到 iframe。我怎样才能做到这一点?

【问题讨论】:

  • 能否请您发布一些代码作为示例。

标签: html css iframe


【解决方案1】:

为此需要 javascript。

document.documentElement.clientHeight 返回客户端的高度。

如果这还不够高,您应该向下滚动:

window.scrollTo(0, 500);

所以可能:

if(document.documentElement.clientHeight < 500) {
    window.scrollTo(0, 500);
}

高度取决于横幅的大小和 iframe 的位置。


如果您只希望 CSS,如果窗口高度不够,您也可以尝试将横幅移动到 iframe 下方。

您可以为此使用媒体查询:

div div {
  width:100px;
  height:100px;
}

div[blue] {
  background-color:blue;
} 

div[green] {
  background-color:green;
}

div[parent] {
  display:flex;
  flex-direction: column-reverse; 
}

@media only screen and (min-width: 600px) {

  div[parent] {
    flex-direction: column; 
  }

}
<div parent>

  <div green>
  green
  </div>

  <div blue>
  blue
  </div>

</div>

【讨论】:

    【解决方案2】:

    您可以使用window.innerHeight来检测屏幕是否太小,然后使用window.scrollTo();将页面向下滚动到iframe。

    maxHeight = 600;
    
    function scrollIfMobile() {
      if (window.innerHeight < maxHeight) {
        var height = document.getElementById("iframe").offsetTop;
        window.scrollTo(0, height);
      }
    }
    div {
      height: 400px;
      background: lightblue;
      margin: 8px;
    }
    <body onload="setTimeout(scrollIfMobile,1)">
      <div>
        Block<br />
      </div>
      <div id="iframe">
        Iframe<br />
      </div>
      <div>
        ...
      </div>
      <div>
        ...
      </div>
    </body>

    Here's a link to my example。尝试调整窗口大小。

    【讨论】:

      猜你喜欢
      • 2010-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-19
      • 1970-01-01
      • 2021-01-11
      • 2022-01-11
      • 2016-10-27
      相关资源
      最近更新 更多