CSS跑馬燈效果是一種通過CSS控制網頁上的燈光效果,可以模擬出閃爍、上下滾動的效果。下面將詳細介紹這種效果的設置方法和實現方法。
一、設置方法
1. 將HTML代碼中的<div>標簽替換為CSS代碼中定義的燈效容器。
2. 在CSS代碼中定義燈效容器的類名和樣式,例如:
```css
.跑馬燈-container {
position: relative;
width: 100%;
height: 500px;
.跑馬燈-container > div {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 100%;
background-color: #ff0000;
animation: 跑馬燈 5s linear infinite;
.跑馬燈-container > div:nth-child(1) {
animation-delay: 0.1s;
.跑馬燈-container > div:nth-child(2) {
animation-delay: 0.2s;
.跑馬燈-container > div:nth-child(3) {
animation-delay: 0.3s;
.跑馬燈-container > div:nth-child(4) {
animation-delay: 0.4s;
.跑馬燈-container > div:nth-child(5) {
animation-delay: 0.5s;
.跑馬燈-container > div:nth-child(6) {
animation-delay: 0.6s;
.跑馬燈-container > div:nth-child(7) {
animation-delay: 0.7s;
.跑馬燈-container > div:nth-child(8) {
animation-delay: 0.8s;
.跑馬燈-container > div:nth-child(9) {
animation-delay: 0.9s;
.跑馬燈-container > div:nth-child(10) {
animation-delay: 1s;
@keyframes 跑馬燈 {
0% {
transform: translateY(0);
100% {
transform: translateY(100%) scale(1);
上述代碼中,`跑馬燈`類名定義了燈效容器的樣式,其中`-container`屬性表示使用絕對定位,`div`標簽定義了每個燈效元素,并設置了動畫效果。
2. 在HTML代碼中添加一個<div>標簽,并設置其內容,例如:
```html
<div>
</div>
通過以上設置方法,就可以在網頁上實現一個閃爍、上下滾動的跑馬燈效果。
二、實現方法
1. 使用JavaScript控制燈效的上下滾動,例如:
```javascript
document.addEventListener('keydown', function(event) {
if (event.code === 'ArrowLeft') {
document.querySelector('.跑馬燈-container > div').style.animationName = '跑馬燈 left 0.5s infinite';
} else if (event.code === 'ArrowRight') {
document.querySelector('.跑馬燈-container > div').style.animationName = '跑馬燈 right 0.5s infinite';
} else if (event.code === 'ArrowUp') {
document.querySelector('.跑馬燈-container > div').style.animationName = '跑馬燈 up 0.5s infinite';
} else if (event.code === 'ArrowDown') {
document.querySelector('.跑馬燈-container > div').style.animationName = '跑馬燈 down 0.5s infinite';
上述代碼中,通過`keydown`事件監聽器來檢測鍵盤上按鍵的按下情況,根據按鍵的按鍵順序來設置不同燈效的動畫效果。
2. 使用CSS3動畫來實現燈效的上下滾動,例如:
```css
.跑馬燈-container {
position: relative;
width: 100%;
height: 500px;
.跑馬燈-container > div {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 100%;
background-color: #ff0000;
animation: 跑馬燈 5s linear infinite;
.跑馬燈-container > div:nth-child(1) {
animation-delay: 0.1s;
.跑馬燈-container > div:nth-child(2) {
animation-delay: 0.2s;
.跑馬燈-container > div:nth-child(3) {
animation-delay: 0.3s;
.跑馬燈-container > div:nth-child(4) {
animation-delay: 0.4s;
.跑馬燈-container > div:nth-child(5) {
animation-delay: 0.5s;
.跑馬燈-container > div:nth-child(6) {
animation-delay: 0.6s;
.跑馬燈-container > div:nth-child(7) {
animation-delay: 0.7s;
.跑馬燈-container > div:nth-child(8) {
animation-delay: 0.8s;
.跑馬燈-container > div:nth-child(9) {
animation-delay: 0.9s;
.跑馬燈-container > div:nth-child(10) {
animation-delay: 1s;
@keyframes 跑馬燈 {
0% {
transform: translateY(0);
100% {
transform: translateY(100%) scale(1);