如何创建一个不需要 JavaScript 而仅仅只需 CSS 的 background-attachment 属性就能实现页面背景固定和滚动效果. 我们看到现在有很多的网站项目使用了视差效果, 通过图片和背景的动态变化以及 JS 脚本来产生视差, 而今天我们只需要 CSS 即可. 查看演示 下载源码 html HTML 结构很简单, 一个 class 为. cd-fixed-bg 的 div 元素用于放置固定背景图, 一个 class 为. cd-scrolling-bg 的 div 元素用于滚动的部分. 我们可以放置多个. cd-fixed-bg 和. cd-scrolling-bg 编组. 目前专业负责前端开发相关职位的招聘, 集中在江浙地区, 看机会的朋友可以联系.
- <main>
- <div class="cd-fixed-bg cd-bg-1">
- <h1><!-- title goes here --></h1>
- </div>
- <div class="cd-scrolling-bg cd-color-2">
- <div 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>
- </div>
- </div>
... 多组 div 并列...
</main>
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.qdfuns.com/article/18301/586cc659f1753cc37b7a5aa86c723f2e.html