CSS3中元素從一種樣式轉變到另一個的時候,爲了使這個過程顯得不那麼唐突,可以加入一些效果,包括過渡時間、延時時間、過渡的運動方式等,這時就可以用過渡,無需使用flash動畫或者JS。
這個過渡有動畫的效果,但是需要手動去觸發,常常跟鼠標事件結合使用。
1、transition-property 設置過渡的屬性,比如:width height background-color
2、transition-duration 設置過渡的時間,比如:1s 500ms(必選,否則不會產生過渡效果)
3、transition-timing-function 設置過渡的運動方式
- linear 勻速
- ease 開始和結束慢速
- ease-in 開始是慢速
- ease-out 結束時慢速
- ease-in-out 開始和結束時慢速
- cubic-bezier(n,n,n,n)
- 比如:cubic-bezier(0.845, -0.375, 0.215, 1.335)
- 曲線設置網站:https://matthewlein.com/ceaser/
4、transition-delay 設置動畫的延遲
5、transition: property duration timing-function delay 同時設置四個屬性
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css" media="screen">
.box{
width: 100px;
height: 100px;
background-color: gold;
/*transition: width 500ms ease 500ms,height 500ms ease 1000ms,background-color 500ms ease 1500ms;*/
transition: all 500ms ease;
}
.box:hover{
width: 200px;
height: 200px;
background-color: green;
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
應用實例:文字遮罩效果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css" media="screen">
.box{
width: 200px;
height: 272px;
margin:50px auto;
border: 1px solid #ddd;
/*超出邊框隱藏掉*/
overflow: hidden;
/*設置父級盒子和相對定位*/
position: relative;
}
.box img{
width: 100%;
height: 272px;
}
.info{
/*相對父級盒子絕對定位,方便控制位置*/
position: absolute;
width:200px;
height:85px;
/*設置盒子背景色和透明度*/
background-color:rgba(0,0,0,0.5);
left: 0;
top:272px;
text-indent: 20px;
color: #fff;
/*設置過渡效果*/
transition: all 500ms cubic-bezier(0.845, -0.375, 0.215, 1.335);
/*多行文字溢出省略號*/
-webkit-line-clamp:4;
display: -webkit-box;
-webkit-box-orient:vertical;
overflow:hidden;
text-overflow: ellipsis;
}
.box:hover .info{
top:187px;
}
</style>
</head>
<body>
<div class="box">
<img src="../images/location_bg.jpg" alt="">
<div class="info">
你若化成風
我幻化成雨
守護你身邊
一笑爲紅顏
你若化成風
我幻化成雨
愛鎖在眉間
似水往昔浮流年乖乖 我的小乖乖
你的樣子太可愛
追你的男生每個都超級厲害
我卻在考慮怎麼Say hi
害羞的我這樣下去要怎麼辦
怎麼辦 愛情甜又酸
我不是Boss
沒有超大的House
如果送你Rose
可不可以給我Chance</div>
</div>
</body>
</html>