CSS背景延伸以填充iOS中的高度,但滚动时有空白区域

use*_*974 2 html css background-image stretch ios

这个CSS让我的背景在iOS中填充100%的屏幕高度但是有一个小问题 - 当你向下滚动时,最初是空白区域,然后当你松开手指并停止滚动背景图像时"调整"并填充100再次屏幕高度的百分比.如果您是第一次继续滚动,则问题不会在同一页面上重新出现.有人可以帮忙吗?谢谢

#background {
  background: url(../img/background.jpg) center repeat-x;
  position: fixed;
  background-size: auto 100%;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: -1
}
Run Code Online (Sandbox Code Playgroud)

smn*_*mnh 13

发生这种情况是因为您的#background元素设置为"跟随"窗口的高度:

#background {
    ...
    position: fixed;
    top: 0;
    bottom: 0;
    ...
}
Run Code Online (Sandbox Code Playgroud)

但是,window当您第一次向下滚动内容时,Safari中的大小会更改460px529px:

在此输入图像描述 在此输入图像描述 在此输入图像描述

从这些屏幕截图中可以看出,当加载网页时,window.innerHeight它等于460px(在iPhone5上).然后,当您的手指触摸屏幕时开始向下滚动页面时,window.innerHeight会增加到529px但内容尚未更新.只有当手指从屏幕上释放时,#background才会使用等于的新窗口高度更新元素529px.

要解决此问题,您应确保#background元素高于初始窗口高度529-460 = 69px.或者#background元素具有恒定的高度529px(或更高):

#background {
    ...
    position: fixed;
    top: 0;
    bottom: -69px;
    ...
}
Run Code Online (Sandbox Code Playgroud)

要么

#background {
    ...
    position: fixed;
    top: 0;
    /* use height instead of bottom */
    height: 529px;
    ...
}
Run Code Online (Sandbox Code Playgroud)

这是修复此问题的最终代码:

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Fixed background</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <link rel="stylesheet" href="css/styles.css?v=1.0">
        <style>
            #background {
                background: url(bkgd.png) repeat;
                position: fixed;
                background-size: 100% auto;
                top: 0;
                left: 0;
                right: 0;
                bottom: -69px;
                z-index: -1;
            }
        </style>
    </head>
    <body>
        <div id="background"></div>
        <div style="height: 5000px;"></div>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)