在CSS3中设置background-image时,可以调用linear-gradient设置渐变。
格式linear-gradient([direction],color-stop1, color-stop2, …)
其中,direction可以是to left/to top/to right/to bottom
例如
1、从左向右由green渐变为yellow
background-image: linear-gradient(to right, green, yellow);
2、按角度进行渐变
按-45度方向渐变
background-image: linear-gradient(-45deg, green, yellow);
3、多重渐变
从左向右渐变,从green渐变为yellow,然后再从yellow渐变为blue。如果设置更多颜色,依次向后渐变。
background-image: linear-gradient(to right, green, yellow, blue);
4、使用透明度渐变
background-image: linear-gradient(to right, rgba(0,0,128,0.5), rgba(0,250,0,0.5));
5、设置渐变的位置
从左向右渐变,最左边宽度的20%为红色,20%处到40%处由红色渐变为黄色,40%处开始由黄色渐变为绿色,最右边的20%为绿色
background-image: linear-gradient(to right, red 20%, yellow 40%, green 80%);
假设宽等于1000px等价于
background-image: linear-gradient(to right, red 200px, yellow 400px, green 800px);
案例一:字体光斑
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
body{
text-align: center;
background: black;
}
h1{
margin-top: 100px;
display: inline-block;
color: rgba(255,255,255,0.5);
font: bold 100px "微软雅黑";
}
h1{
background: linear-gradient(120deg,rgba(255,255,255,0) 50px, rgba(255,255,255,1) 100px, rgba(255,255,255,0) 150px);
background-repeat: no-repeat;
background-clip: -webkit-text;
-webkit-background-clip: text;
}
</style>
</head>
<body>
<h1>苍鹰蛟龙</h1>
</body>
<script type="text/javascript">
var h1 = document.querySelector("h1")
var flag = -50;
setInterval(function(){
flag+=2;
if(flag == 500){
flag = -50;
}
h1.style.backgroundPosition = flag + "px";
})
</script>
</html>
效果如下:
案例二:发廊灯
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#wrap{
width: 50px;
height: 400px;
border: 1px solid;
margin: 100px auto;
overflow: hidden;
}
#wrap > .inner{
height: 800px;
background: repeating-linear-gradient(45deg, black 0px, black 10px, white 10px, white 20px);
}
</style>
</head>
<body>
<div id="wrap">
<div class="inner">
</div>
</div>
</body>
<script type="text/javascript">
var inner = document.querySelector("#wrap > .inner");
var flag = 0;
setInterval(function(){
flag++;
if(flag==400){
flag=0;
}
inner.style.marginTop = -flag + "px";
},10)
</script>
</html>
效果如下: