滚动视差
最近在一个公众号看到滚动视差效果,觉得挺有意思的,相比传统滚动的显示效果让人耳目一新。
来源:http://web.jobbole.com/95068/
主要是运用background-attachment属性,该属性有四个值,分别是scroll(默认)、fixed、local和inherit
scroll:背景相对于元素固定,背景随页面滚动而滚动,背景和内容绑定
fixed:背景相对于视口固定,所以页面滚动而背景不动,相当于背景设置在body上
local:背景相对于元素固定(和scroll很像,但是有区别)
inheerit :继承
scroll 和local:举一个栗子
<div class="content">
<div class="box">
<p>1</p>
</div>
</div>
对于一个div包裹若干个p标签,设置div的背景图片
1:local和scroll的区别
滚动条是出现在box里的,当我们鼠标在box中移动滚动条时,P元素是在滚动的,这时在box里给background-attachment:scroll,这时候,背景图不会随元素内容的滚动而滚动。,如果给的是background-attachment:local,因为背景图片是相对于元素内容定位,开始是固定的,当出现滚动条后背景图随之开始移动。
2:fixed
fixed是相对于视口,与元素没有关系。因为网页只有一个视口,所以图片是不会滚动的,直到元素不可见。
相关:background-size:cover 设置图片缩放来适应整个容器(100%和cover的差别:100%按容器比例撑满,图片会变形,cover按照图片比例缩放,可能会裁剪、失真)
background-size 的取值说明:
auto:默认值,保持背景图片的原始高度和宽度
<length >:设置具体的值,可以改变图片大小,第一个值设置宽度,第二个值设置高度
<percentage> :计算相对于背景定位区域的百分比。此值只能使用在块级元素上,同样是2个参数,第一个值设置宽度,第二个值设置高度。若只设置第一个值,第二个默认为auto。
cover:保持图像的横纵比例将图片缩放成完全覆盖定位区域的最小大小
contain:此时会保持图像的横纵比例将图片缩放成适合背景定位区域的最大大小(不设置background-repeat: no-repeat的话会将图片平铺占据整个容器)
background-position:用于定位图片位置,有2个参数,如果使用1个,另一个默认为center,即为50%;左上角为0% 0%,右下角为 100% 100%。可以混合使用%和position的值。
<style type="text/css">
section{
height: 100vh;
background: rgba(0,0,0,.7);
color:#fff;
line-height: 100vh;
text-align: center;
font-size: 20vh;
}
.img1{
background-image:url('img/1.jpg');
background-attachment: fixed;
background-size: contain;
background-repeat: no-repeat;
background-position: center center;
}
.img2{
background-image: url('img/2.jpg');
background-attachment: fixed;
background-size: cover;
background-position:center center;
}
.img3{
background-image: url('img/3.jpg');
background-attachment: fixed;
background-size: cover;
background-position: center center;
}
</style>
<body>
<section class="word">Header</section>
<section class="img1">IMG1</section>
<section class="word">Content1</section>
<section class="img2">IMG2</section>
<section class="word">Content2</section>
<section class="img3">IMG3</section>
<section class="word">Footer</section>
<script>
</script>
</body>
vh:相对于视口,视口被均分为100个单位。
上一篇: 上下滑动的常见视差效果
下一篇: 嵌入式程序优化 (1)--内联霓虹灯组装