今天突然有个搞电商的朋友,问我能不能实现一个背景不动,页面滚动的小特效,当时大脑一顿操作,各种实现方法想了好多,
第一个想到的就是js控制,突然想到了css的background-attachment 属性,就想试试。
background-attachment的属性:(注意:一定要与背景搭配使用)
background-attachment的兼容性:
background-attachment的兼容性还是不错的,但对于ios和部分移动端的兼容还是有点问题的。
ios系统和某些移动端background-attachment:fixed不兼容性,没有任何效果,但可以hack一下就可以了,代码如下:
ps:想在哪个标签加背景,可以在它class后:before.
body:before {
content: ' ';
position: fixed;
z-index: -1;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: url(path/to/image) center 0 no-repeat;
background-size: cover;
}
最后献上我的代码(很简单):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.bg-content-1 {
height: 719px;
width: 1920px;
background: url(http://gdp.alicdn.com/imgextra/i2/453276963/TB2cBTft7OWBuNjSsppXXXPgpXa_!!453276963.jpg);
background-repeat: no-repeat;
background-position: center;
background-attachment: fixed;
}
.bg-content-2 {
height: 719px;
width: 1920px;
background: url(http://gdp.alicdn.com/imgextra/i2/453276963/TB2oHlIgVooBKNjSZFPXXXa2XXa_!!453276963.jpg);
background-repeat: no-repeat;
background-position: center;
background-attachment: fixed;
}
</style>
</head>
<body>
<div class="content">
<div class="bg-content-1">
<img src="http://gdp.alicdn.com/imgextra/i1/453276963/TB2tk9hlS8YBeNkSnb4XXaevFXa_!!453276963.png" />
</div>
<div style="width: 100%;height: 350px;text-align: center;margin-top: 345px;">
我纯粹就是占空的
</div>
<div class="bg-content-2">
<img src="http://gdp.alicdn.com/imgextra/i1/453276963/TB2tk9hlS8YBeNkSnb4XXaevFXa_!!453276963.png" />
</div>
</div>
</body>
</html>