今天,咱們用比較簡潔的CSS3來實現翻轉效果。css
當鼠標滑過包含塊時,元素總體翻轉180度,以實現「正」「反」面的切換。app
分析:.container
,.flip
爲了實現動畫效果作準備。.front
,.back
各包裹一張圖片。
實現該效果的HTML以下:less
<div class="container"> <div class="flip"> <div class="front"> <img src="images/pic00.jpg" alt=""> </div> <div class="back"> <img src="images/pic01.jpg" alt=""> </div> </div> </div>
爲了實現以上效果,先進行元素佈局。給.front
,.back
相對.flip
進行絕對定位,讓他們在相同位置重疊。
佈局部分代碼以下:佈局
.container,.front,.back{width:380px;height:270px;} .flip{position:relative;} .front,.back{position:absolute;top: 0px;left: 0px;}
設置以後咱們發現.back
的圖片在.front
的上面,所以給.front
設置.fornt{z-index:2;}
動畫
注意:不要爲了防止元素溢出設置overflow
屬性,這將致使3D效果沒法實現。ui
w3 spec中描述:spa
The following CSS property values require the user agent to create a flattened representation of the descendant elements before they can be applied, and therefore force the used value of transform-style to flat:3d
overflow: any value other than visible.code
opacity: any value less than 1.orm
filter: any value other than none.
clip: any value other than auto.
(1) 爲了實現動畫效果首先給祖先元素.container
,.flip
設置如下屬性,以觸發3d效果和設置動畫:
.container{perspective:1000;transform-style:preserve-3d;} .flip{transition:0.6s;transform-style:preserve-3d;}
(2)接着,爲了讓圖畫翻轉時不露出背面,給.front
,.back
設置backface-visibility
屬性:.front,.back{backface-visibility:hidden;}
(3)爲了讓鼠標滑過包含塊時,包含塊翻轉180度,以實現「正」「反」面的切換。給背面的元素設置transform:rotateY(-180deg)
,這時咱們將沒法看到.back
。
(4)最後,當用戶的鼠標滑過.container
包含塊時,.flip
翻轉180度,這樣,.front
翻轉180度,因爲背面是hidden
,沒法看見;而.back
翻轉180度後,回到0度,以正面示人,這樣咱們就能看到背面了。
代碼以下:
.container{perspective:1000;transform-style:preserve-3d;} .container,.front,.back{width:380px;height:270px;} .flip{position:relative;transition:0.6s;transform-style:preserve-3d;} .front,.back{position:absolute;top: 0px;left: 0px;backface-visibility:hidden;} .front{z-index:2;} .back{transform:rotateY(-180deg);} .container:hover .flip{transform:rotateY(180deg);}
垂直效果與水平翻轉殊途同歸。可是若是你只是把rotateY換成rotateX,那麼你會發現圖片是以頂部的那條線翻轉的。
請注意:在上面的CSS代碼中,我並未給.flip
設置寬高,因此當給.flip
應用transform:rotateY(180deg)
時,按照默認的transform-origin
值,是以元素的中心點爲基本點翻轉的。這裏.flip
的高度是0,因此固然是以頂部的那條線爲基礎翻轉。因此解決的辦法有二:
給.flip
設置和.front
,.back
相同的寬高。
給.flip
設置transform-origin:100% 135px/*高度的一半*/
屬性。
OK,這樣你就會發現垂直翻轉是你想要的效果了!
(1)最外層元素設置perspective
以實現3D效果。
(2)當鼠標滑過最外層元素時,第二包裹層翻轉180度,同時設置過渡速度。
(3)兩個翻轉塊絕對定位,以至實現相同位置的疊加。同時設置backface-visibility
避免在實現動畫效果時露出背面。
(4)給.front
設置z-index
屬性使它在寫代碼和展現時都在前面。
(5)讓.back
最開始就翻轉180度,以背面示人。
(1)爲了讓兩個尺寸不一的圖片在包裹塊中大小一致,使用了overflow
屬性,沒法實現3d效果。解決方法:給img
設置width:100%;height:100%;
(2)沒有意識到.flip
的高度爲0,因此在垂直翻轉時標準點錯誤致使效果不同。
(3)多寫才能發現多的錯誤,才知道怎麼找錯誤,怎麼解決錯誤。
Talk is cheap,show me the code.