我有一个网页,上面有一个带有一些内容的巨大横幅图像。在它下面,我有一个用于 youtube 视频的 iframe。该网页是响应式的,但是当我在移动设备上打开它时,标题太大,用户需要向下滚动才能查看视频。
我想要实现的是当用户在移动设备上打开网页时,它应该自动向下滚动到 iframe。我怎样才能做到这一点?
You can use window.innerHeight to detect whether the screen is too small, then use window.scrollTo(); to scroll the page down to the 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. Try resizing the window.
为此,您将需要 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>