利用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,755 Responses

  1. DouglasHoapy表示:

    Промокод Фонбет при регистрации https://www.bigpowernews.ru/files/pgs/aktualnuy_promokod_fonbet_pri_registracii.html
    Промокод Фонбет при регистрации предоставляет новым пользователям уникальную возможность получить приветственные бонусы. Например, при вводе промокода ‘GIFT200’ в специальное поле при регистрации, пользователи могут получить бесплатные ставки или другие бонусы. Эти промокоды делают процесс начала игры более привлекательным и помогают новым игрокам успешно стартовать на платформе.

  2. Coreyges表示:

    Discover the world of excitement at Pin Up Casino, the world’s leading online casino. The official website Pil up offers more than 4,000 slot machines. Play online for real money or for free using the working link today

  3. 888starzMt表示:

    Все свежие акции и предложения от 888Starz ждут вас, присоединяйтесь к игре прямо сейчас http://led119.ru/forum/user/107642/

  4. ArthurKib表示:

    https://indianpharmacy.company/# indianpharmacy com

  5. Coreyges表示:

    Discover the world of excitement at Pin Up Casino, the world’s leading online casino. The official website Slot pick up offers more than 4,000 slot machines. Play online for real money or for free using the working link today

  6. Arthurjen表示:

    Ретрит http://ретриты.рф международное обозначение времяпрепровождения, посвящённого духовной практике. Ретриты бывают уединённые и коллективные; на коллективных чаще всего проводится обучение практике медитации.

  7. RobertJaw表示:

    娛樂城推薦與優惠詳解

    在現今的娛樂世界中,線上娛樂城已成為眾多玩家的首選。無論是喜歡真人遊戲、老虎機還是體育賽事,每個玩家都能在娛樂城中找到自己的樂趣。以下是一些熱門的娛樂城及其優惠活動,幫助您在選擇娛樂平台時做出明智的決定。

    各大熱門娛樂城介紹
    1. 富遊娛樂城
    富遊娛樂城以其豐富的遊戲選擇和慷慨的優惠活動吸引了大量玩家。新會員只需註冊即可免費獲得體驗金 $168,無需儲值即可輕鬆試玩。此外,富遊娛樂城還提供首存禮金 100% 獎勵,最高可領取 $1000。

    2. AT99娛樂城
    AT99娛樂城以高品質的遊戲體驗和優秀的客戶服務聞名。該平台提供各種老虎機和真人遊戲,並定期推出新遊戲,讓玩家保持新鮮感。

    3. BCR娛樂城
    BCR娛樂城是一個新興的平台,專注於提供豐富的體育賽事投注選項。無論是足球、籃球還是其他體育賽事,BCR都能為玩家提供即時的投注體驗。

    熱門遊戲推薦
    WM真人視訊百家樂
    WM真人視訊百家樂是許多玩家的首選,該遊戲提供了真實的賭場體驗,並且玩法簡單,容易上手。

    戰神賽特老虎機
    戰神賽特老虎機以其獨特的主題和豐富的獎勵機制,成為老虎機愛好者的最愛。該遊戲結合了古代戰神的故事背景,讓玩家在遊戲過程中感受到無窮的樂趣。

    最新優惠活動
    富遊娛樂城註冊送體驗金
    富遊娛樂城新會員獨享 $168 體驗金,無需儲值即可享受全場遊戲,讓您無壓力地體驗不同遊戲的魅力。

    VIP 日日返水無上限
    富遊娛樂城為 VIP 會員提供無上限的返水優惠,最高可達 0.7%。此活動讓玩家在遊戲的同時,還能享受額外的回饋。

    結論
    選擇合適的娛樂城不僅能為您的遊戲體驗增色不少,還能通過各種優惠活動獲得更多的利益。無論是新會員還是資深玩家,都能在這些推薦的娛樂城中找到適合自己的遊戲和活動。立即註冊並體驗這些優質娛樂平台,享受無限的遊戲樂趣!

  8. adas car cal表示:

    The passion for Car Cal ADAS is infectious. Reading the post has inspired me to learn more.

  9. Coreyges表示:

    Discover the world of excitement at Pin Up Casino, the world’s leading online casino. The official website Game pic up offers more than 4,000 slot machines. Play online for real money or for free using the working link today

  10. Профессиональный сервисный центр по ремонту фото техники от зеркальных до цифровых фотоаппаратов.
    Мы предлагаем: диагностика и ремонт фотоаппаратов
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  11. Coreyges表示:

    Discover the world of excitement at Pin Up Casino, the world’s leading online casino. The official website Slot pick up offers more than 4,000 slot machines. Play online for real money or for free using the working link today

  12. El comercio de opciones binarias es una modalidad de trading en la que los inversores apuestan si el valor de un activo se mantendra o cambiara. Brokers regulados como Quotex ofrecen herramientas avanzadas para el trading de opciones binarias. Con estrategias adecuadas, es posible mejorar las predicciones en el trading de opciones binarias. Opciones binarias trading se ha vuelto frecuente en paises como Mexico y en todo el mundo.
    quotex descargar que son las opciones binarias .

  13. Профессиональный сервисный центр по ремонту фото техники от зеркальных до цифровых фотоаппаратов.
    Мы предлагаем: ремонт цифровых фотоаппаратов
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  14. MauriceGueda表示:

    mexico drug stores pharmacies: mexico drug stores pharmacies – buying prescription drugs in mexico online

  15. Josephfub表示:

    mexico drug stores pharmacies pharmacies in mexico that ship to usa mexican border pharmacies shipping to usa

  16. Профессиональный сервисный центр по ремонту планшетов в Москве.
    Мы предлагаем: ремонт планшетов на дому
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  17. Если вы искали где отремонтировать сломаную технику, обратите внимание – профи услуги

  18. ArchieWaize表示:

    Pin up casino official Game pic up casino website – login and play online

  19. CallumGed表示:

    Le бесплатный промокод на 1xbet. Enregistrez-vous des a present avec notre code promotionnel 1xBet valable jusqu’en 2024 pour beneficier d’un bonus de 200% sur votre premier depot. Utilisez le code de bonus lors de l’ouverture de votre nouveau compte 1xbet afin de recevoir votre bonus de bienvenue de 130$. L’enregistrement est autorise pour les personnes ayant atteint l’age de 18 ans et residant dans les pays ou l’activite du bookmaker n’est pas limitee au niveau legislatif.

  20. ArthurKib表示:

    https://indianpharmacy.company/# Online medicine order

  21. DouglasHoapy表示:

    Фрибет промокод Фонбет https://mcv26.ru/news/aktualnuy_promokod_fonbet_pri_registracii.html
    Фрибет промокоды от Фонбет предоставляют пользователям возможность сделать бесплатные ставки. Примером такого промокода является ‘GIFT200’, который активирует фрибеты для новых игроков. Эти промокоды позволяют пользователям попробовать свои силы в ставках без риска потери собственных средств, увеличивая шансы на выигрыш.

  22. ArchieWaize表示:

    Pin up casino official Slot pick up casino website – login and play online

  23. DanielGed表示:

    Qu’est-ce qu’une «Vitrine de codes promotionnels»?
    Ceci est une section speciale sur le site du bookmaker официальный сайт 1хбет промокод, qui contient tous les codes promotionnels actuels. Sur la vitrine, les joueurs sont disponibles codes bonus pour les Paris sportifs, pour la section avec le jeu. Chaque code peut etre echange contre des points promo en fonction des denominations.

  24. ArchieWaize表示:

    Pin up casino official Game pic up casino website – login and play online

  25. Wcrfonert表示:

    Two key court decisions define the limitations of…
    Helpful treatment is available when you buy lexapro insomnia to make your sexual life strengthen.
    The primary-care provider recommended that the patient see an ear, nose, and throat specialist, thinking perhaps the problem could be found there.

  26. Drstobeese表示:

    peoples pharmacy: guardian pharmacy ibuprofen – zovirax online pharmacy

  27. elzbncrhn表示:

    After signing up for one of the best paying online casinos, it’s time to pick which games to play. To make this easier, we’ve researched which online slots, table, and specialty games have the highest RTP and provide the best casino payouts. Stick with these titles to enjoy better value and higher payouts online. Marcus Kirschen Welcome to Coushatta Casino4Fun. Our all-new online gaming site that’s bigger and better than ever before! Offering a no deposit free spins bonus is a great way for casinos to help players get familiar with a slot. Players also have a chance to win real money on slots with no deposit if they choose to play these games. Depending on the offer from the participating casino, you can get free spins funds or free cash you can use on slots. Use your free spins, land high-paying symbols, wager your wins, and take home your cash!
    https://uniform-wiki.win/index.php?title=Play_poker_for_free_and_win_real_money
    Transparency: We believe in transparency and integrity. Our predictions are based on objective analysis, and we provide detailed explanations for each tip, so you can understand the reasoning behind our recommendations. Sharp Football Analysis, LLC does not endorse, recommend or support illegal betting or gambling under any circumstances. All information on this site is for entertainment purposes only and is not intended to be used in any direct or indirect violation of local, state, federal or international law(s). Are you ready to take your football betting game to the next level? Look no further! Our team of expert tipsters is here to provide you with carefully crafted predictions, backed by thorough analysis and insider knowledge. The tipsters’ expertise on our site is wide-range and opens doors for us to prepare betting tips for a stack of matches and market types. Our predictions incorporate betting markets for Over Under bets (you must predict how many goals will be scored – Over or Under 0,5; 1,5; 2,5; 3,5;4,5), Both teams to score (you must guess if either team will score a goal – Yes No, Goal No Goal), Draw no Bet and correct score.

發佈留言

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