利用TweenMax針對HTML頁面製作動畫 – CSS篇

前一篇文章跟大家分享了如何利用TweenMax在HTML裡面製作基礎的動畫,接下來示範如何利用TweenMax來控制CSS的效果,當然前置作業跟之前相同,這邊就不多提,但在TweenMax內需加上CSS的控制項目,大致的語法如下:

TweenMax.to(物件,動畫秒數,{css:{樣式名稱:值},ease:動畫模式});

其實跟前篇文章大致相同,只是在動畫的部分要利用「css:{}」這段語法來包含欲更改的樣式,以下是更改寬度和高度的範例:

TweenMax.to(div,1,{css:{width:100, height:200},ease:Expo.easeOut});

接下來為各位示範一下在網頁上製作動畫的範例,這是第一個範例,主要為Div移動的效果,下面是本範例整個網頁的程式碼:

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>GreenSock HTMLTweening CSS Move</title>
    <style type="text/css">
        #box {
            height: 200px;
            width: 200px;
            position: absolute;
            background-color: #9CF;
        }

        /* box div 的樣式 */
    </style>
    <script src="src/minified/TweenMax.min.js"></script>
    <script language="javascript">
        window.onload = moveFn;

        function moveFn() {
            var div = document.getElementById("box"); /* 利用div變數儲存ID名稱為box的物件 */
            var divX = "0px" /* 利用變數儲存div預設的x位置 */
            var divY = window.innerHeight / 2 - 100 + "px"; /* 利用變數儲存div預設的y位置 */
            var moveX = window.innerWidth / 2 - 100 + "px"
            div.style.left = divX div.style.top = divY TweenMax.to(div, 1, {
                css: {
                    left: moveX
                },
                ease: Expo.easeOut
            });
        }
    </script>
</head>
<body style="background-color:#FFF">
    <div id="box"></div>
</body>
</html>

延續上面,接下來第二個範例程式碼大致與上面相同,只是增加了div變形和旋轉的效果,可以看得出來除了CSS本身的樣式之外,還可以利用TweenMax所提供的scale和rotation來製作動畫,下面是本範例整個網頁的程式碼:

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>GreenSock HTMLTweening CSS Move</title>
    <style type="text/css">
        #box {
            height: 200px;
            width: 200px;
            position: absolute;
            background-color: #9CF;
        }

        /* box div 的樣式 */
    </style>
    <script src="src/minified/TweenMax.min.js"></script>
    <script language="javascript">
        window.onload = moveFn;

        function moveFn() {
            var div = document.getElementById("box"); /* 利用div變數儲存ID名稱為box的物件 */
            var divX = "0px" /* 利用變數儲存div預設的x位置 */
            var divY = window.innerHeight / 2 - 100 + "px"; /* 利用變數儲存div預設的y位置 */
            var moveX = window.innerWidth / 2 - 100 + "px"
            div.style.left = divX div.style.top = divY TweenMax.to(div, 1, {
                css: {
                    left: moveX
                },
                ease: Expo.easeOut
            });
            TweenMax.to(div, 1, {
                css: {
                    scale: 2,
                    rotation: 90
                },
                delay: 1,
                ease: Expo.easeOut
            });
        }
    </script>
</head>
<body style="background-color:#FFF">
    <div id="box"></div>
</body>
</html>

接下來第三個案例加上了更換背景顏色的部分,背景顏色更換的部分,要注意語法跟css的背景顏色樣式名稱有所不同,下面是本範例整個網頁的程式碼:

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>GreenSock HTMLTweening CSS Move</title>
    <style type="text/css">
        #box {
            height: 200px;
            width: 200px;
            position: absolute;
            background-color: #9CF;
        }

        /* box div 的樣式 */
    </style>
    <script src="src/minified/TweenMax.min.js"></script>
    <script language="javascript">
        window.onload = moveFn;

        function moveFn() {
            var div = document.getElementById("box"); /* 利用div變數儲存ID名稱為box的物件 */
            var divX = "0px" /* 利用變數儲存div預設的x位置 */
            var divY = window.innerHeight / 2 - 100 + "px"; /* 利用變數儲存div預設的y位置 */
            var moveX = window.innerWidth / 2 - 100 + "px"
            div.style.left = divX div.style.top = divY TweenMax.to(div, 1, {
                css: {
                    left: moveX
                },
                ease: Expo.easeOut
            });
            TweenMax.to(div, 1, {
                css: {
                    scale: 2,
                    rotation: 90
                },
                delay: 1,
                ease: Expo.easeOut
            });
            TweenMax.to(div, 3, {
                css: {
                    backgroundColor: "#EEEEEE"
                },
                delay: 2,
                ease: Expo.easeOut
            });
        }
    </script>
</head>
<body style="background-color:#FFF">
    <div id="box"></div>
</body>
</html>

接下來第四個案例是利用TimelineMax來輔助製作這段動畫,可以看的出來上面範例都在使用delay來決定動畫播放順序,但在前面的文章中有提到TimelineMax可以協助我們來掌握動畫播放的順序,所以本範例更改為利用TimelineMax來製作動畫,下面是本範例整個網頁的程式碼:

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>GreenSock HTMLTweening CSS Move</title>
    <style type="text/css">
        #box {
            height: 200px;
            width: 200px;
            position: absolute;
            background-color: #9CF;
        }

        /* box div 的樣式 */
    </style>
    <script src="src/minified/TweenMax.min.js"></script>
    <script language="javascript">
        window.onload = moveFn;

        function moveFn() {
            var div = document.getElementById("box"); /* 利用div變數儲存ID名稱為box的物件 */
            var divX = "0px" /* 利用變數儲存div預設的x位置 */
            var divY = window.innerHeight / 2 - 100 + "px"; /* 利用變數儲存div預設的y位置 */
            var moveX = window.innerWidth / 2 - 100 + "px"
            div.style.left = divX div.style.top = divY
            var tMax = new TimelineMax;
            tMax.to(div, 1, {
                css: {
                    left: moveX
                },
                ease: Expo.easeOut
            });
            tMax.to(div, 1, {
                css: {
                    scale: 2,
                    rotation: 90
                },
                ease: Expo.easeOut
            });
            tMax.to(div, 3, {
                css: {
                    backgroundColor: "#EEEEEE"
                },
                ease: Expo.easeOut
            });
        }
    </script>
</head>
<body>
    <div id="box"></div>
</body>
</html>

看了上面的幾個案例之後,在這邊也來製作幾個比較完整的範例供大家參考,首先是第一個範例,利用文字連結來更換div內容的效果,下面是本範例整個網頁的程式碼:

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>GreenSock HTMLTweening CSS Sample 1</title>
    <style type="text/css">
        * {
            padding: 0px;
            margin: 0px;
        }

        body {
            font-size: 13px;
        }

        #box {
            height: 450px;
            width: 600px;
            margin-left: auto;
            margin-right: auto;
            background-color: #EEE;
        }

        /* box div 的樣式 (內容div) */
        #content {
            padding: 10px 10px 0px 10px;
            line-height: 26px;
            width: 500px;
            margin-left: auto;
            margin-right: auto;
        }

        /* content div 的樣式 (內容p) */
        #btn {
            height: 30px;
            width: 600px;
            text-align: center;
            margin-left: auto;
            margin-right: auto;
            padding-top: 10px;
        }

        #btn a {
            margin: 5px;
        }

        /* btn div 的樣式 (下方文字連結div) */
    </style>
    <script src="src/minified/TweenMax.min.js"></script>
    <script language="javascript">
        var intro1 =
            "<p style='text-align:center;'><img src='ford/p1.jpg' style='border:1px solid #000; background-color:#FFFFFF'></p><p>全新導入的運動模式(S-Mode),讓變速箱升檔時機往後遞延,以維持較高的引擎轉速再進行換檔,充分提升駕駛加速感受。在中高速行駛時,運動模式可提供更及時的降檔反應,使引擎仍可保持在扭力峰值的轉速範圍內,同時讓動力輸出對油門的反應更加靈敏,整體引擎動力的運動性大幅提升,創造最動感的馳騁體驗。</p>";
        var intro2 =
            "<p style='text-align:center;'><img src='ford/p2.jpg' style='border:1px solid #000; background-color:#FFFFFF'></p><p>高科技的雙離合器變速箱擁有自排、手排、上坡、下坡、高海拔修正、怠速、斜坡潛滑減緩、緊急安全八大模式。以手排齒輪箱為基礎,搭配平行排列濕式雙離合器機構,能在極短時間內完成換檔,沒有傳統自排變速箱的扭力頓挫感,加速也更加敏捷平順,且操作介面與傳統自排一樣簡易方便。</p>";
        var intro3 =
            "<p style='text-align:center;'><img src='ford/p3.jpg' style='border:1px solid #000; background-color:#FFFFFF'></p><p>全新高傳真CD/MP3/WMA音響主機,具備DSP數位音場設定、Clip失真檢測功能、智慧型音量控制、高傳真音效調整、AST電台頻道自動掃描儲存功能、位於中央扶手中AUX-IN功能的孔狀插槽與USB插槽(包含一般MP3裝置與iPod主機連結功能),是目前同等級房車中與iPod整合性最高的機種。</p>"; /* 以上為利用三個變數儲存不同的網頁內容 */
        window.onload = moveFn; /* 網頁載入時執行moveFn */
        function moveFn() {
            var div = document.getElementById("box"); /* 利用div變數儲存ID名稱為box的物件 */
            var intro = document.getElementById("content"); /* 利用intro變數儲存ID名稱為content的物件 */
            intro.innerHTML = intro1; /* 設定content的div內容為第一個連結的內容 */
            var tMax = new TimelineMax;
            tMax.from(div, 0.5, {
                css: {
                    scale: 0
                },
                ease: Expo.easeOut
            });
            tMax.from(intro, 1, {
                css: {
                    alpha: 0
                }
            }); /* 以動畫的方式呈現內容 */
        }

        function changeFn(no) {
            var div = document.getElementById("box"); /* 利用div變數儲存ID名稱為box的物件 */
            var intro = document.getElementById("content"); /* 利用intro變數儲存ID名稱為content的物件 */
            var tMax = new TimelineMax;
            tMax.to(intro, 0, {
                css: {
                    alpha: 0
                }
            });
            tMax.to(div, 0.5, {
                css: {
                    scale: 0
                },
                ease: Expo.easeOut
            });
            tMax.to(div, 0.5, {
                css: {
                    scale: 1
                },
                ease: Expo.easeOut
            });
            tMax.to(intro, 1, {
                css: {
                    alpha: 1
                }
            });
            switch (no) {
                case 1:
                    intro.innerHTML = intro1;
                    break;
                case 2:
                    intro.innerHTML = intro2;
                    break;
                case 3:
                    intro.innerHTML = intro3;
                    break;
            }
        }
    </script>
</head>
<body style="background-color:#FFF">
    <div id="box">
        <p id="content"></p>
    </div>
    <div id="btn"><a href="javascript:;" onClick="changeFn(1)">運動模式</a><a href="javascript:;"
            onClick="changeFn(2)">雙離合器</a><a href="javascript:;" onClick="changeFn(3)">整合音響</a></div>
</body>
</html>

接下來的範例是利用TweenMax來設計讓一個div永遠保持在畫面左邊中間的效果,下面是本範例整個網頁的程式碼:

<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title>GreenSock HTMLTweening CSS Sample 2</title>
    <script src="src/minified/TweenMax.min.js"></script>
    <script language="javascript">
        window.onload = init; //網頁載入時執行init
        window.onscroll = init; //捲動網頁時執行init
        window.onresize = init; //網頁更改尺寸時執行init
        function init(){
            var div=document.getElementById("bannerDiv");
            //利用div變數儲存網頁上ID為bannerDiv的物件(即為放圖片的Div)
            var banner=document.getElementById("tweenMax");
            //利用banner變數儲存網頁上ID為tweenMax的物件(即為圖片本身)
            positionY= window.innerHeight/2-banner.height+window.pageYOffset;
            //利用PositionY儲存在畫面中Div應該出現的座標位置
            TweenMax.to(div,1,{css:{top:positionY},ease:Elastic.easeOut});
            //利用TweenMax將Div移動到上面所儲存的位置
        } 
    </script>
    <style type="text/css">
        #bannerDiv {
            height: 54px;
            width: 108px;
            position: absolute;
        }
    </style>
</head>

<body style="background-color:#FFF">
    <div id="bannerDiv"><img src="mw_tweenmax.gif" name="tweenMax" width="108" height="54" id="tweenMax" /></div>
    <div
        style="width:400px; height:2000px; background-color:#EEE; margin-left:auto; margin-right:auto; font-size:13px; text-align:center">
        網頁內容</div>
</body>

</html>

看完了上面幾個範例之後,相信大家可以利用TweenMax搭配HTML和Javascript來取代更多需要Flash才可以完成的效果了,祝大家設計順利!

You may also like...

8,702 Responses

  1. Robertgaw表示:

    Declan Rice https://declan-rice.prostoprosport-fr.com Footballeur anglais, milieu defensif du club d’Arsenal et de l’equipe nationale equipe d’Angleterre. Originaire de Kingston upon Thames, Declan Rice s’est entraine a l’academie de football de Chelsea des l’age de sept ans. En 2014, il devient joueur de l’academie de football de West Ham United.

  2. RaymondSmero表示:

    Mohamed Salah Hamed Mehrez Ghali https://mohamed-salah.prostoprosport-fr.com Footballeur egyptien, attaquant du club anglais de Liverpool et l’equipe nationale egyptienne. Considere comme l’un des meilleurs footballeurs du monde

  3. Donaldmes表示:

    Jogo do Tigre https://jogo-do-tigre.prostoprosport-br.com is a simple and fun game that tests your reflexes and coordination. In this game you need to put your finger on the screen, pull out the stick and go through each peg. However, you must ensure that the stick is the right length, neither too long nor too short.

  4. Tmpzpq表示:

    buy disopyramide phosphate generic – disopyramide phosphate over the counter cost thorazine 100mg

  5. Joshuaknima表示:

    Kylian Mbappe Lotten https://kylian-mbappe.prostoprosport-fr.com Footballeur francais, attaquant du Paris Saint-Germain et capitaine de l’equipe de France. Le 1er juillet 2024, il deviendra joueur du club espagnol du Real Madrid.

  6. Georgedof表示:

    Bernardo Silva https://bernardo-silva.prostoprosport-fr.com Portuguese footballer, midfielder. Born on August 10, 1994 in Lisbon. Silva is considered one of the best attacking midfielders in the world. The football player is famous for his endurance and performance. The athlete’s diminutive size is more than compensated for by his creativity, dexterity and foresight.

  7. mebel wvEr表示:

    Перетяжка мягкой мебели

    https://www.credly.com/users/username.962aabc5/badges .

  8. Davidodosy表示:

    Philip Walter Foden https://phil-foden.prostoprosport-fr.com better known as Phil Foden English footballer, midfielder of the Premier club -League Manchester City and the England national team. On December 19, 2023, he made his debut at the Club World Championship in a match against the Japanese club Urawa Red Diamonds, starting in the starting lineup and being replaced by Julian Alvarez in the 65th minute.

  9. DanielFlurn表示:

    Sweet Bonanza https://sweet-bonanza.prostoprosport-fr.com is an exciting slot from Pragmatic Play that has quickly gained popularity among players thanks to its unique gameplay, colorful graphics and the opportunity to win big prizes. In this article, we’ll take a closer look at all aspects of this game, from mechanics and bonus features to strategies for successful play and answers to frequently asked questions.

  10. Michaelreath表示:

    Karim Mostafa Benzema https://karim-benzema.prostoprosport-fr.com French footballer, striker for the Saudi club Al-Ittihad . He played for the French national team, for which he played 97 matches and scored 37 goals.

  11. BradleyBurdy表示:

    Achraf Hakimi Mou https://achraf-hakimi.prostoprosport-fr.com Moroccan footballer, defender of the French club Paris Saint-Germain “and the Moroccan national team. He played for Real Madrid, Borussia Dortmund and Inter Milan.

  12. BryanUnelo表示:

    In January 2010, Harry Kane https://harry-kane.prostoprosport-fr.com received an invitation to the England U-team for the first time 17 for the youth tournament in Portugal. At the same time, the striker, due to severe illness, did not go to the triumphant 2010 European Championship for boys under 17 for the British.

  13. Jeffreyjax表示:

    Antoine Griezmann https://antoine-griezmann.prostoprosport-fr.com French footballer, striker and midfielder for Atletico Madrid. Player and vice-captain of the French national team, as part of the national team – world champion 2018. Silver medalist at the 2016 European Championship and 2022 World Championship.

  14. Andrewswots表示:

    Jude Victor William Bellingham https://jude-bellingham.prostoprosport-fr.com English footballer, midfielder of the Spanish club Real Madrid and the England national team. In April 2024, he won the Breakthrough of the Year award from the Laureus World Sports Awards. He became the first football player to receive it.

  15. Larrypef表示:

    Son Heung Min https://sonheung-min.prostoprosport-br.com South Korean footballer, striker and captain of the English Premier League club Tottenham Hotspur and the Republic of Korea national team. In 2022 he won the Premier League Golden Boot. Became the first Asian footballer in history to score 100 goals in the Premier League

  16. DonaldVox表示:

    Laure Boulleau https://laure-boulleau.prostoprosport-fr.com French football player, defender. She started playing football in the Riom team, in 2000 she moved to Isere, and in 2002 to Issigneux. All these teams represented the Auvergne region. In 2003, Bullo joined the Clairefontaine academy and played for the academy team for the first time.

  17. 匿名訪客表示:

    Откройте путь к лучшей версии себя – кликните по ссылке
    на %D0%9E%D0%9F%D0%A1%D0%A3%D0%98%D0%9C%D0%9E%D0%9B%D0%9E%D0%93

  18. RodneyKip表示:

    Kyle Andrew Walker https://kylewalker.prostoprosport-br.com English footballer, captain of the Manchester City club and the England national team. In the 2013/14 season, he was on loan at the Notts County club, playing in League One (3rd division of England). Played 37 games and scored 5 goals in the championship.

  19. JeffreyDem表示:

    Jack Peter Grealish https://jackgrealish.prostoprosport-br.com English footballer, midfielder of the Manchester City club and the England national team. A graduate of the English club Aston Villa from Birmingham. In the 2012/13 season he won the NextGen Series international tournament, playing for the Aston Villa under-19 team

  20. Aifoni_taSt表示:

    ремонт телефонов айфон плюс https://www.iphonepochinka.by .

  21. CarlosAcard表示:

    Khvicha Kvaratskhelia https://khvicha-kvaratskhelia.prostoprosport-br.com Georgian footballer, winger for Napoli and captain of the Georgian national team. A graduate of Dynamo Tbilisi. He made his debut for the adult team on September 29, 2017 in the Georgian championship match against Kolkheti-1913. In total, in the 2017 season he played 4 matches and scored 1 goal in the championship.

  22. Jefferysance表示:

    Damian Emiliano Martinez https://emiliano-martinez.prostoprosport-br.com Argentine footballer, goalkeeper of the Aston Villa club and national team Argentina. Champion and best goalkeeper of the 2022 World Cup.

  23. Топ-5 материалов для перетяжки мебели, проверенных временем
    Как преобразить интерьер с минимальными затратами, перетянутую мебель мечтали ваши друзья
    Топ-3 причины для перетяжки мебели в доме, пригласите в гости дизайнера
    Вдохновляющие идеи для перетяжки мебели, применяемые в современном дизайне
    Как не ошибиться с выбором ткани для перетяжки мебели, запомнить
    перетяжка мебели “КакСвоим”.

  24. Hyjunj表示:

    buy generic depakote online – cordarone 200mg us purchase topiramate pill

  25. Phillipspult表示:

    Roberto Firmino Barbosa de Oliveira https://roberto-firmino.prostoprosport-br.com Brazilian footballer, attacking midfielder, forward for the Saudi club “Al-Ahli”. Firmino is a graduate of the Brazilian club KRB, from where he moved to Figueirense in 2007. In June 2015 he moved to Liverpool for 41 million euros.

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。