CSS3實現輪播動畫代碼

來源:互聯網
上載者:User

輪播動畫簡單實現

現在的前端,越來越注重使用者互動和體驗,有很多動畫和效果是很常見的,如本篇要講的主題:輪播動畫。這和以前經常聽到的一個名詞–”跑馬燈“效果一樣。在CSS3出來之前,都是通過JavaScript實現的動畫,現在我們完全可以使用CSS3,效能有很大的提升,相容性也已經很不錯,尤其是移動端。

CSS3實現動畫效能會有極大提升,特別是當頁面動畫較多或定時器較多時。

html結構:

    <h2>CSS實現</h2>    <p class="wrapper-css">        <p class="container-css marquee">            <p>今天</p>            <p>明天</p>            <p>後天</p>            <p>今天</p><!-- 輔助元素,為實現迴圈輪播 -->        </p>    </p>

可以看到,依然需要在後面添加一個重複輔助元素,實現迴圈輪播效果。

CSS代碼:

    // 輪播動畫        @-webkit-keyframes marquee {            0% {                -webkit-transform: translate3d(0, 0, 0);            }            27% {                -webkit-transform: translate3d(0, 0, 0);            }            33% {                -webkit-transform: translate3d(0, -100%, 0);            }            60% {                -webkit-transform: translate3d(0, -100%, 0);            }            67% {                -webkit-transform: translate3d(0, -200%, 0);            }            94% {                -webkit-transform: translate3d(0, -200%, 0);            }            100% {                -webkit-transform: translate3d(0, -300%, 0);            }        }        @keyframes marquee {            0% {                transform: translate3d(0, 0, 0);            }            /* 100/3 * (2s/2.5s) => 26.7% => 27% */            27% {                transform: translate3d(0, 0, 0);            }            /* 100/3 =>33.3 => 33% */            33% {                transform: translate3d(0, -100%, 0);            }            60% {                transform: translate3d(0, -100%, 0);            }            67% {                transform: translate3d(0, -200%, 0);            }            94% {               transform: translate3d(0, -200%, 0);            }            100% {                transform: translate3d(0, -300%, 0);            }        }        .wrapper-css {            width: 200px;            height: 30px;            margin: 10px;            overflow: hidden;        }        .container-css {            height: 30px;            -webkit-animation: marquee 7.5s linear infinite;/* 2.5s(2s + 0.5s) * 3 => 7.5s */            animation: marquee 7.5s linear infinite;        }        .container-css p {            width: 100%;            height: 30px;            margin: 0;            line-height: 30px;            font-size: 18px;        }

如上,我們使用CSS3定義動畫主要畫面格,並結合transform位移實現無縫輪播動畫,通過移動容器實現輪播效果,主要需要根據輪播元素計算動畫主要畫面格點

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.