在CSS中,我們可以使用@keyframes
規(guī)則來創(chuàng)建一個(gè)兩秒的動(dòng)畫,然后在animation
屬性中引用這個(gè)動(dòng)畫,以下是一個(gè)簡單的示例,展示如何在頁面打開時(shí)彈出一個(gè)彈窗:
1、我們需要?jiǎng)?chuàng)建一個(gè)彈窗的HTML結(jié)構(gòu),這通常是一個(gè)div
元素,包含一些文本和其他內(nèi)容。
<div id="popup" class="hidden"> <h1>歡迎來到我的網(wǎng)站!</h1> <p>這是一個(gè)彈窗示例。</p> <button>關(guān)閉彈窗</button> </div>
2、我們使用CSS來設(shè)置彈窗的樣式和動(dòng)畫,我們定義一個(gè)@keyframes
動(dòng)畫,用于控制彈窗的出現(xiàn)和消失:
@keyframes popup-animation { 0% { transform: scale(0); opacity: 0; } 50% { transform: scale(1); opacity: 1; } 100% { transform: scale(1); opacity: 0; } }
3、我們?cè)?code>#popup元素上應(yīng)用這個(gè)動(dòng)畫:
#popup { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); animation: popup-animation 2s; }
4、我們使用JavaScript來控制彈窗的顯示和隱藏,我們可以監(jiān)聽DOMContentLoaded
事件,然后在頁面加載完成后顯示彈窗:
document.addEventListener('DOMContentLoaded', function() { var popup = document.getElementById('popup'); var closeButton = document.querySelector('button'); closeButton.addEventListener('click', function() { popup.style.display = 'none'; // 隱藏彈窗 }); });
在這個(gè)示例中,彈窗會(huì)在頁面打開時(shí)自動(dòng)顯示,并在用戶點(diǎn)擊“關(guān)閉彈窗”按鈕時(shí)隱藏,CSS動(dòng)畫控制了彈窗的出現(xiàn)和消失效果。