box-shadow實現的打點效果
簡介
box-shadow理論上可以生成任意的圖形效果,當然也就可以實現點點點的loading效果了。
實現原理
html代碼,首先需要寫如下html代碼以及class類名:
訂單提交中<span class="dotting"></span>
css代碼
.dotting { display: inline-block; min-width: 2px; min-height: 2px; box-shadow: 2px 0 currentColor, 6px 0 currentColor, 10px 0 currentColor; /* for IE9+, ..., 3個點 */ animation: dot 4s infinite step-start both; /* for IE10+, ... */ *zoom: expression(this.innerHTML = '...'); /* for IE7. 若無需兼容IE7, 此行刪除 */ } .dotting:before { content: '...'; } /* for IE8. 若無需兼容IE8, 此行以及下一行刪除*/ .dotting::before { content: ''; } /* for IE9+ 覆蓋 IE8 */ :root .dotting { margin-right: 8px; } /* for IE9+,FF,CH,OP,SF 占據空間*/ @keyframes dot { 25% { box-shadow: none; } /* 0個點 */ 50% { box-shadow: 2px 0 currentColor; } /* 1個點 */ 75% { box-shadow: 2px 0 currentColor, 6px 0 currentColor; /* 2個點 */ } }
這里用到了currentColor這個關鍵字,IE9+瀏覽器支持,其可以讓CSS生成的圖形的顏色跟所處環境的color屬性值一樣,也就是跟文字顏色一樣。
各瀏覽器實現的效果如圖所示:
支持CSS3 animation
動畫的瀏覽器顯示的就是打點動畫效果;對於不支持的瀏覽器,IE7/IE8顯示的是真實的字符...
, IE9瀏覽器雖然也是CSS3生成,但是是靜態的,沒有動畫效果;此乃漸進兼容。
不足之處
雖然幾乎所有瀏覽器都有模有樣,但是,從效果上講,還是有瑕疵的,IE10+以及FireFox瀏覽器下的點的邊緣有些虛(參見下截圖),雖然CSS代碼並沒有設置盒陰影模糊。這種羽化現象可以讓IE以及FireFox在大數值盒陰影時候效果更接近photoshop的陰影效果;但是,在小尺寸陰影時候,並不是我們想要的。
border + background實現的打點效果
實現原理
html代碼
訂單提交中<span class="dotting"></span>
css代碼
.dotting { display: inline-block; width: 10px; min-height: 2px; padding-right: 2px; border-left: 2px solid currentColor; border-right: 2px solid currentColor; background-color: currentColor; background-clip: content-box; box-sizing: border-box; animation: dot 4s infinite step-start both; *zoom: expression(this.innerHTML = '...'); /* IE7 */ } .dotting:before { content: '...'; } /* IE8 */ .dotting::before { content: ''; } :root .dotting { margin-left: 2px; padding-left: 2px; } /* IE9+ */ @keyframes dot { 25% { border-color: transparent; background-color: transparent; } /* 0個點 */ 50% { border-right-color: transparent; background-color: transparent; } /* 1個點 */ 75% { border-right-color: transparent; } /* 2個點 */ }
說明:
- 同樣是4秒動畫,每秒鍾顯示1個點;
- IE7/IE8實現原理跟上面
box-shadow
方法一致,都是內容生成,如果無需兼容IE7/IE8, 可以按照第一個例子CSS代碼注釋說明刪除一些CSS; currentColor
關鍵字可以讓圖形字符化,必不可少;- 最大功臣是CSS3
background-clip
屬性,可以讓IE9+瀏覽器下左右padding
沒有背景色,於是形成了等分打點效果。 box-sizing
是讓現代瀏覽器和IE7/IE8占據寬度完全一樣的功臣:IE7/IE8實際寬度是width+padding-right
為12
像素,其他現代瀏覽器為width+margin-left
也是12
像素;- 這里CSS代碼主要用來展示原理,故沒有顯示
-webkit-animation
以及@-webkit-keyframes
私有前綴,實際目前還是需要的;
參考地址:再說CSS3 animation實現點點點loading動畫
https://github.com/tawian/text-spinners