利用background-attachment做视差滚动效果

视差滚动(Parallax Scrolling)是指让多层背景以不同的速度移动,形成立体的运动效果,带来非常出色的视觉体验。作为今年网页设计的热点趋势,越来越多的网站应用了这项技术。

不明白的可以先看看eBay上的效果:http://www.ebay.com/new/

其实就是固定背景不让它随着滚动轴移动,但包含背景的容器是跟着滚动的,所造成的视觉差异看起来就像跟转换场景一样。(这个解释别嫌混乱…)

在CSS中定义背景滚动方式的属性是backgroud-attacthment

background-attachment -- 定义背景图片随滚动轴的移动方式

  • 取值: scroll | fixed | inherit
    • scroll: 默认值。背景图像会随着页面其余部分的滚动而移动。
    • fixed: 当页面的其余部分滚动时,背景图像不会移动。
    • inherit: 规定应该从父元素继承 background-attachment 属性的设置。
    • 初始值: scroll
    • 继承性: 否
    • 适用于: 所有元素

附带w3c的链接:http://www.w3school.com.cn/css/pr_background-attachment.asp

浏览器的支持性:

测试了chrome,opera,safari,firefox,ie7-8都是可以的,所以就是说IE6下不行~

在IE6下使用这个属性,需要把background-attachment:fixed放置于body或html当中,就是说你说在其它标签里面是没用。上面的w3c里可以看得到效果就是因为它是放在body里的。

这是我自己做的一个demo,点击可以下载

代码:

 1 <!doctype html>
 2 <html>
 3     <head>
 4         <meta charset="utf-8">
 5         <title>滚动视觉差示例</title>
 6         <style>
 7             *{
 8                 padding:0;
 9                 margin:0
10             }
11             body{
12                 text-align:center;
13                 background-attachment:fixed;
14             }
15             #main{
16                  1280px;
17                 margin:auto
18             }
19             .header{
20                 background:#fff;
21                 padding: 10px 0
22             }
23             .bg-attachment{
24                 background:url(6.jpg) center center no-repeat;
25                 box-shadow:0 7px 18px #000000 inset,0 -7px 18px #000000 inset;
26                 -webkit-box-shadow:0 7px 18px #000000 inset,0 -7px 18px #000000 inset;
27                 -moz-box-shadow: 0 7px 18px #000000 inset,0 -7px 18px #000000 inset;
28                 -o-box-shadow: 0 7px 18px #000000 inset,0 -7px 18px #000000 inset;
29                 -ms-box-shadow: 0 7px 18px #000000 inset,0 -7px 18px #000000 inset;
30                 background-attachment:fixed;
31             }
32             .bg-attachment .shadow{
33                 80%;
34                 height:700px;
35                 overflow:hidden;
36                 margin:auto;
37             }
38             .div2{
39                 background:url(qingz.jpg) center center no-repeat;
40                 background-attachment:fixed;
41             }
42         </style>
43     </head>
44     <body>
45         <div id="main">
46             <div class="header">
47                 <img src="5.jpg">
48             </div>
49             <div class="bg-attachment">
50                 <div class="shadow"></div>
51             </div>
52             <div class="header">
53                 <img src="qi.jpg">
54             </div>
55             <div class="bg-attachment div2">
56                 <div class="shadow"></div>
57             </div>
58         </div>
59     </body>
60 </html>
原文地址:https://www.cnblogs.com/wbxjiayou/p/5403408.html