天天看點

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

【開發小技巧】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>      

​輸出:

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

方法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 onload="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>      

輸出:

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

本文完~