css的2d轉換十分強大,能夠在不使用js的情況下,實現頁面的元素與用戶之間更多動態的交互,增強用戶體驗。其中使用最多的就是hover偽類。
1、創建一個頁面的div元素:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>2d轉換測試</title> </head> <body> <div id="fr"> <div class="de">我是測試文本</div> <div class="de">我是測試文本</div> <div class="de">我是測試文本</div> <div class="de">我是測試文本</div> </div> </body> </html>
2、css中給定元素的樣式:
#fr{ width: 500px; height: 600px; border: 1px solid gray; margin: 20px auto; }
.de{ width:100px; height:100px; border:1px solid green; margin: 10px auto; }
3、瀏覽器解析的效果:
4、給第一個正方形加入鼠標點擊后的效果css:
.de:first-child:hover{ transform: translate(0px,-5px);
transition: transform 1s; }
效果:
鼠標移動到正方形區域后,小方塊會向上移動5px,有過渡效果;離開小方塊后,立即回到原位,沒有過渡效果;
另外一種寫法:
.de:first-child{ transition: transform 1s; } .de:first-child:hover{ transform: translate(0px,-5px); }
將transition過渡效果寫在被選中的整個元素中,出現的效果:
鼠標移動到正方形區域后,小方塊會向上移動5px,有過渡效果;離開小方塊后,小方塊會到原始位置,有過渡效果。
原理:將過渡效果transition寫在hover偽類中,鼠標進入時,hover效果會應用transition效果;鼠標移出,屬於非hover,沒有過渡效果;即,元素移動過程中,有過渡效果;元素回到原始位置,沒有過渡效果。將transition過渡寫在整個元素中,會在元素整個移動過程中起到過渡效果。
5、給每個小方塊加入動畫效果完整的css:
#fr{ width: 500px; height: 600px; border: 1px solid gray; margin: 20px auto; } .de{ width:100px; height:100px; border:1px solid green; margin: 10px auto; } .de:first-child{ transition: transform 1s; } .de:first-child:hover{ transform: translate(0px,-5px); } .de:nth-child(2){ transition: transform 1s; } .de:nth-child(2):hover{ transform: rotate(360deg); } .de:nth-child(3){ transition: transform 1s; } .de:nth-child(3):hover{ transform: skew(30deg ,30deg); } .de:last-child{ transition: transform 1s; } .de:last-child:hover{ transform: scale(1.05,1.05); }
效果:
所有的 transform transition都需要進行瀏覽器兼容性適配,這里僅僅是為了演示,沒有對瀏覽器進行適配。