现在的位置: 首页 > web前端 > 正文

使用CSS制作的页面背景固定和滚动效果

2020年02月12日 web前端 ⁄ 共 1235字 ⁄ 字号 评论关闭

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

HTML

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

<main> <p class="cd-fixed-bg cd-bg-1"> <h1><!-- title goes here --></h1> </p> <p class="cd-scrolling-bg cd-color-2"> <p class="cd-container"> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolore incidunt suscipit similique, dolor corrupti cumque qui consectetur autem laborum fuga quas ipsam doloribus sequi... </p> </p> </p> ...多组p并列... </main>


CSS

那么如何实现背景固定和滚动效果呢?一开始,我想使用jQuery,也许我先应该让一个p固定位置,然后当滚动页面时改变背景图片,但是觉得不好弄。而简单的我们使用几行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%; }

以上就上有关使用CSS制作的页面背景固定和滚动效果的相关介绍,要了解更多滑动内容请登录学步园。

抱歉!评论已关闭.