Appearance
背景图固定效果在移动端失灵?
TIP
在 PC 端设置的背景图固定效果(background-attachment:fixed),在 iOS 和部分安卓手机上完全失效?图片会随着页面滚动而滑动,体验不是很好。
平时的写法:
css
body{
width:100%;
background-image:url("图片的地址");
background-repeat:no-reapeat;
background-position:center;
background-attachment:fixed;
z-index:-1;
}
body{
width:100%;
background-image:url("图片的地址");
background-repeat:no-reapeat;
background-position:center;
background-attachment:fixed;
z-index:-1;
}
这种写法在 PC 端和部分现代浏览器上效果很好,但在 iOS 和一些移动端浏览器中,背景图会跟着页面一起滚动,完全失去了固定的效果。
兼容的写法:
css
body:before{
content:'';
position:fixed;
z-index:-1;
top:0;
right:0;
bottom:0;
left:0;
background:url("图片的地址") center 0 no-repeat;
background-size:cover;
}
body:before{
content:'';
position:fixed;
z-index:-1;
top:0;
right:0;
bottom:0;
left:0;
background:url("图片的地址") center 0 no-repeat;
background-size:cover;
}
经过多次尝试,我发现用伪元素可以完美解决这个问题