如何使页面向下滚动并专注于iframe



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

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

为此,您将需要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>

您可以使用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>

这是我的示例的链接。尝试调整窗口大小。

最新更新