1. 程式人生 > >CSS實現3D正方體動態旋轉效果【原始碼+GIF圖】

CSS實現3D正方體動態旋轉效果【原始碼+GIF圖】

小夥伴們看到那些頁面上炫酷的正方體,是不是都覺得美美的很精緻,很想自己動手寫一個屬於自己的,但是又學業繁忙而找不到時間去實現,今天我就為大家寫一個,噠噠噠,廢話不多說,開始上程式碼~ 
額,要不先說說它的實現原理吧,方便理解,嘿嘿。 

實現原理:

  • transition-property 要應用過渡的css屬性
  • transition-duration 過渡發生的時長
  • transition-timing-function 過渡過程速度變化的設定

可設定值:

linear(勻速)ease(緩慢開始,緩慢結束。預設) ease-in(緩慢開始) ease-out(緩慢結束) ease-in-out(緩慢開始,緩慢結束,但與ease速度不同)

  • transition-delay 過渡何時開始
  • transition 以上屬性簡寫

  使用:

  不同瀏覽器需要在屬性前加字首:chrome、Safari 需要加 -webkit-,Firefox字首-moz-,IE字首-ms-,Opera字首-o-

perspective:建立3D場景,實現透視效果,值為物品與螢幕距離

  perspective-origin:子元素在檢視中的位置,X和Y值表示(注意:perspective和perspective-origin都要在實現3D效果元素的父元素中設定)

  transform-style:規定如何在 3D 空間中呈現被巢狀的元素(可設定為flat或preserve-3d)

  transform-origin:旋轉中心

    X軸可設定為:left | center | right

    Y軸可設定為:top | center | bottom

    Z軸設定在Z軸上的位置:length px

  本例中用到的方法有translateX(px),translateY,translateZ,表示在XYZ軸上移動和rotateX(deg),rotateY,rotateZ繞XYZ軸旋轉。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>
Title</title> <style> *{ margin: 0; padding: 0; } body{ perspective: 600px;; } .box{ width: 400px; height: 400px; margin:100px auto; position:relative; } .box:hover ul{ transform: rotateX(360deg) rotateY(360deg); } ul{ width: 400px; height: 400px; transform: rotateX(-30deg) rotateY(0deg) ; transform-style: preserve-3d; transition: all 10s linear; } li{ list-style: none; width: 200px; height: 200px; border: 1px solid #000; background:rgba(255,56,49,0.5); position: absolute; margin: auto; left: 0; right: 0; bottom:0; top: 0;; } ul :nth-child(1){ transform:rotateY(0deg) translateZ(100px); } ul :nth-child(2){ transform: rotateY(-90deg) translateZ(100px); } ul :nth-child(3) { transform: rotateY(-180deg) translateZ(100px); } ul :nth-child(4){ transform: rotateY(-270deg) translateZ(100px); } ul :nth-child(5){ transform: rotatex(90deg) translateZ(100px); } ul :nth-child(6){ transform: rotatex(90deg) translateZ(-100px); } </style> </head> <body> <div class="box"> <ul> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> </div> </body> </html>

效果圖: