css制作的页面背景固定和滚动效果图_CSS制作的页面背景固定和滚动效果

更新时间:2020-03-25    来源:页面特效    手机版     字体:

【www.bbyears.com--页面特效】

如何创建一个不需要Javascript而仅仅只需CSS的background-attachment属性就能实现页面背景固定和滚动效果。我们看到现在有很多的网站项目使用了视差效果,通过图片和背景的动态变化以及js脚本来产生视差,而今天我们只需要CSS即可。


HTML结构很简单,一个class为.cd-fixed-bg的div元素用于放置固定背景图,一个class为.cd-scrolling-bg的div元素用于滚动的部分。我们可以放置多个.cd-fixed-bg和.cd-scrolling-bg编组。

 代码如下


   
       


     
 
   
       
           


                Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolore incidunt suscipit similique, dolor corrupti cumque qui consectetur autem laborum fuga quas ipsam doloribus sequi...
           


         
     
    ...多组div并列...

CSS

那么如何实现背景固定和滚动效果呢?一开始,我想使用jQuery,也许我先应该让一个div固定位置,然后当滚动页面时改变背景图片,但是觉得不好弄。而简单的我们使用几行CSS就能做到,将要固定的元素的背景background-size值设置为cover,background-attachment的值设置为fixed,这样就实现了单页面的背景固定和滚动效果。请看以下代码:

 代码如下

body, html, main {
    /* important */
    height: 100%;
}
 
.cd-fixed-bg {
    min-height: 100%;
    background-size: cover;
    background-attachment: fixed;
    background-repeat: no-repeat;
    background-position: center center;
}
 
.cd-fixed-bg.cd-bg-1 {
  background-image: url("../img/cd-background-1.jpg");
}
.cd-fixed-bg.cd-bg-2 {
  background-image: url("../img/cd-background-2.jpg");
}
.cd-fixed-bg.cd-bg-3 {
  background-image: url("../img/cd-background-3.jpg");
}
 
 
.cd-scrolling-bg {
    min-height: 100%;
}

本文来源:http://www.bbyears.com/wangyetexiao/89532.html

热门标签

更多>>

本类排行