小程序裏須要一個像下面的loading,原生的沒有,引入別的組件庫又太大,全部決定本身寫個。css
動態的實現原理是給8個小圓圈設置透明度由大變小的動畫,每一個圓圈設置不一樣的動畫啓動時間。佈局的實現原理是父元素設置爲position: relative
, 每一個圓圈設置樣式爲position: absolute; left: xx; top: xx; right: xx; bottom: xx
。 經過給left/right/top/bottom設置不一樣的值將其均勻的分佈在一個圓圈上。html代碼以下:html
<view class="q-loading-dot-warp"> <view class="dot dot1"></view> <view class="dot dot2"></view> <view class="dot dot3"></view> <view class="dot dot4"></view> <view class="dot dot5"></view> <view class="dot dot6"></view> <view class="dot dot7"></view> <view class="dot dot8"></view> </view>
提及來簡單,可是給它們賦值的時候沒有經驗,第一次用理科生的思惟簡單將圓三等分計算座標,每每8個圓圈就圍成了一個菱形/正方形。。。就像下面這樣
css3
後來在簡書上看到 同窗po的文章 css3實現18中loading效果, 按照JRd3的代碼確實能夠實現很好看的效果,可是當我想換一換loading圓圈大小的時候,樣式就崩了,通過分析,他們的座標是存在某種數學關係的,以下圖所示,在豎直或橫線上的座標可經過50%定位,斜線上的座標如圖中所示,其中w是矩形的寬高或者說是8個小圓圈所圍成的大園的半徑。
公式推導以下: 小程序
具體css代碼以下:佈局
$width: 64px; $height: 64px; $dotWidth: 10px; $dotHeight: 10px; $radius: 5px; $offset: 9.37px; @function getLeft( $x ) { @return ($width/4)*$x; } @function getTop( $y ) { @return ($height/4)*$y; } @keyframes changeOpacity { from { opacity: 1; } to { opacity: .2; } } .q-loading { position: fixed; top: 0; left: 0; right: 0; bottom: 0; .q-loading-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(255, 255, 255, .5); } .q-loading-content { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); width: $width; height: $height; z-index: 2; } .dot { width: 10px; height: 10px; position: absolute; background-color: #0033cc; border-radius: 50% 50%; opacity: 1; animation: changeOpacity 1.04s ease infinite; } .dot1 { left: 0; top: 50%; margin-top: -$radius; animation-delay: 0.13s; } .dot2 { left: $offset; top: $offset; animation-delay: 0.26s; } .dot3 { left: 50%; top: 0; margin-left: -$radius; animation-delay: 0.39s; } .dot4 { top: $offset; right: $offset; animation-delay: 0.52s; } .dot5 { right: 0; top: 50%; margin-top: -$radius; animation-delay: 0.65s; } .dot6 { right: $offset; bottom: $offset; animation-delay: 0.78s; } .dot7 { bottom: 0; left: 50%; margin-left: -$radius; animation-delay: 0.91s; } .dot8 { bottom: $offset; left: $offset; animation-delay: 1.04s; } }
代碼使用scss定義了大圓和小圓圈的半徑,無論改爲多大隻須要更改變量,下面樣式無需改變。
經過這個公式計算的看起來就很像圓形了
動畫
假設動畫持續時間爲 t, 圓圈個數爲 c, 某個小圓圈的位置爲 i (好比上面 i 取 1~8),那麼小圈相繼啓動的時間爲 i * t/cspa