【要求】
一個div,配合 css3 或者 js 實現紅綠燈切換的效果。
【思路】
使用 css3,要實現紅綠燈顏色的變換必然要用到 animation 動畫,通過 keyframes 控制顏色的漸變效果。
使用 js,則需要使用定時器,在定時器的方法中改變 div 的類名或者直接修改樣式,來控制顏色的變換。
【實現】
首先看dom結構,非常簡單,一個div:
<div class="hld" id="hld"></div>
基本樣式:
.hld { width: 100px; height: 100px; border-radius: 50%; background: red; } .red { background: red; } .green { background: green; }
【css3實現】
.hld { width: 100px; height: 100px; border-radius: 50%; background: red; animation: hld 1s ease-in-out 1s infinite; } @keyframes hld { 0% { background: red; } 100% { background: green; } }
思路很簡單,定義兩個關鍵幀,0%的時候設置背景色為紅色,100%的時候設置為綠色,需要注意的地方就是動畫的寫法,這里簡單復習一下:
keyframes
@keyframes animationname {keyframes-selector {css-styles;}}
- animationname: 動畫名稱,在 animation 屬性值中使用
- keyframes-selector: 動畫時長的百分比,關鍵詞 "from" 和 "to",等價於 0% 和 100%。
- css-styles: 一個或多個合法的 css 樣式屬性
【注意】

animation
div { animation: myfirst 5s linear 2s infinite alternate; /* Firefox: */ -moz-animation: myfirst 5s linear 2s infinite alternate; /* Safari 和 Chrome: */ -webkit-animation: myfirst 5s linear 2s infinite alternate; /* Opera: */ -o-animation: myfirst 5s linear 2s infinite alternate; }
- animation-name: 規定 @keyframes 動畫的名稱。
- animation-duration: 規定動畫完成一個周期所花費的秒或毫秒。默認是 0
- animation-timing-function: 規定動畫的速度曲線。默認是 "ease" —— linear | ease | ease-in | ease-out | ease-in-out)
- animation-delay: 規定動畫何時開始(延遲時間)。默認是 0
- animation-iteration-count: 規定動畫被播放的次數。默認是 1 —— n | infinite
- animation-direction: 規定動畫是否在下一周期逆向地播放。默認是 "normal" —— normal | alternate(輪流反向播放)
- animation-play-state: 規定動畫是否正在運行或暫停。默認是 "running" —— paused | running
- animation-fill-mode: 規定對象動畫時間之外的狀態。
【效果】

【js實現】
// 獲取目標節點 var node = document.getElementById('hld'); // 定義顏色變換方法 function turnColor () { // 在定時器中動態設置 div 類名 setTimeout(function () { node.className = 'hld red' setTimeout(function () { node.className = 'hld green' // 遞歸執行方法 setTimeout(turnColor, 0) }, 1000) }, 1000) } turnColor()
【優化】
盡管上述 js 代碼已經能夠符合要求,但是從 api 設計的角度上來說,沒有提供統一的簡單的執行入口,因此還可以繼續優化,如下:
// 獲取目標節點方法 function TargetEle (node) { this.node = document.getElementById(node) } // 設置原型方法 TargetEle.prototype.turn = function () { // 獲取目標節點 let thisNode = this.node; // 主動執行顏色變換方法 (function turnColor () { setTimeout(() => { thisNode.className = 'hld red' setTimeout(() => { thisNode.className = 'hld green' setTimeout(turnColor(), 0) }, 1000) }, 1000) })() } // 生成原型實例的方法 function getEle (node) { let ele = new TargetEle(node) return ele } // api: 提供節點id, 執行對應方法即可 getEle('hld').turn()
【效果】

【總結】
一個簡單的效果,考察了 css3 的使用,在使用 js 實現過程中,體現了對定時器、函數原型、以及api設計的了解和掌握程度。
【參考】

