【开发小技巧】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>

输出:

本文完~

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