今天,咱们用比较简洁的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.