【開發小技巧】08—如何使用CSS在頁面加載時創建淡入效果?

英文 | https://www.geeksforgeeks.org/

翻譯 | web前端開發(ID:web_qdkf)

使用動畫和過渡屬性在使用CSS的頁面加載中創建淡入效果。

方法1:使用CSS動畫屬性:CSS動畫由2個關鍵幀定義。一個將不透明度設置爲0,另一個將不透明度設置爲1。當動畫類型設置爲easy時,動畫在頁面中平滑淡入淡出。

此屬性應用於body標籤。每當頁面加載時,都會播放此動畫,並且頁面看起來會淡入。可以在animation屬性中設置淡入的時間。

代碼如下:

body {     animation: fadeInAnimation ease 3s     animation-iteration-count: 1;     animation-fill-mode: forwards; }
@keyframes fadeInAnimation {     0% {         opacity: 0;     }     100% {         opacity: 1;      } }

例:

<!DOCTYPE html> <html>
<head>     <title>         How to create fade-in effect         on page load using CSS     </title>
    <style>         body {             animation: fadeInAnimation ease 3s;             animation-iteration-count: 1;             animation-fill-mode: forwards;         }         @keyframes fadeInAnimation {             0% {                 opacity: 0;             }             100% {                 opacity: 1;             }         } </style> </head>
<body>     <h1 style="color: green">         GeeksForGeeks     </h1>
    <b>         How to create fade-in effect         on page load using CSS     </b>
    <p>         This page will fade in         after loading     </p> </body>
</html>

輸出:

方法2:使用過渡屬性,並在加載主體時將不透明度設置爲1:在此方法中,可以將主體初始設置爲不透明度0,並且每當更改該屬性時,過渡屬性都將用於爲其設置動畫。

加載頁面時,使用onload事件將不透明度設置爲1。由於transition屬性,現在更改不透明度將在頁面中消失。淡入的時間可以在transition屬性中設置。

代碼如下:

body {     opacity: 0;     transition: opacity 5s; }

例:

<!DOCTYPE html> <html>
<head>     <title>         How to create fade-in effect         on page load using CSS     </title>
    <style>         body {             opacity: 0;             transition: opacity 3s;         } </style> </head>
<body οnlοad="document.body.style.opacity='1'">
    <h1 style="color: green">         GeeksForGeeks     </h1>
    <b>         How to create fade-in effect         on page load using CSS     </b>
    <p>         This page will fade in         after loading     </p> </body>
</html>

輸出:

本文完~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章