想讓某個元素「跳」出來引起注意嗎?本文示範如何擴充一個 flash 方法,讓指定元素在原本顏色與目標顏色之間來回變換,達到閃爍的效果,呼叫方式非常直覺。
做法是用 animate 在兩個顏色之間做兩段各佔一半時間的補間動畫:
代碼如下:
1 2 3 4 5 6 7 8 jQuery.fn.flash = function( color, duration ) { var current = this.css( 'color' ); this.animate( { color: 'rgb(' + color + ')' }, duration / 2 ); this.animate( { color: current }, duration / 2 ); } // https://www.jb51.net Then use the above function as: $( '#importantElement' ).flash( '255,0,0', 1000 );
使用前記得先記下元素目前的 color,動畫結束後再還原回去,這樣就不會破壞原本的樣式。要注意的是,jQuery 核心的 animate 預設不能補間顏色,需搭配 jQuery UI 或 color 動畫插件才能生效。
希望本文所述能對你的 jQuery 開發有所幫助。