作項目會碰到作一些簡單的css3動畫,就把一些簡單的動畫屬性玩了一遍,今天作了一個css3實現的滑塊,以爲還蠻好玩的,就記錄一下實現方式。css
首先看一下作的是個什麼東東:html
就是一個開關,點了以後上面的滑塊從左邊跑到右邊so easy的小動畫。css3
圖1 滑動前的效果web
圖2 滑動後的效果css3動畫
css3新屬性就不在這裏羅列了,想了解看看教程以後就會了。這裏用到transition屬性,因此粗略解釋一下。transition屬性,w3譯爲過渡,是元素從一種樣式逐漸改變爲另外一種的效果。你設定一個元素的初始樣式,再設定最後的樣式,而後你能夠控制transition的過渡速度,延遲時間等等。那麼怎麼觸發transition呢。MDN上是這麼解釋的:app
The transition
CSS property is a shorthand property for transition-property
, transition-duration
, transition-timing-function
, and transition-delay
. It enables you to define the transition between two states of an element. Different states may be defined using pseudo-classes like:hover
or :active
or dynamically set using JavaScript.動畫
也就是說,transition在該元素上hover,active或者用js來觸發transition,這樣你才能看到transition效果。那麼咱們動手作一個開關吧(∩_∩)this
利用transition作一個開關不難,寫好一個初始樣式和transition以後的樣式就能夠了,但問題是你怎麼用css觸發這個transition事件呢,去google上一搜,就看到不少抖機靈的同窗作的奇淫異巧(哭衰我怎麼沒想到)。隨手看到一個方法,記錄一下。google
既然點擊的時候完成,那麼咱們放一個複選框(checkbox)隱藏掉這個chckbox就好了呀~而後吧這個checkbox跟你要作動畫的元素(好比label)綁定在一塊兒,點擊transition元素的時候,等同於點擊checkbox,就這麼機靈的出發了transition。spa
大概思想就是這樣子的,當時看到這個方法的時候只是以爲,不少時候,作一些沒嘗試的東西,多google,去吸收別人的優秀經驗,還有就是要動腦子,奇淫異巧這個東西,就是你思惟模式要跳躍,要敢於嘗試就能夠啦(∩_∩)(∩_∩)好噠,感慨完了放代碼吧。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <style type = "text/css"> .switch{ background-color:#9fcaf4; height: 26px; width: 0; border-radius: 12px; transition:all 1s ease; } .bg{ display: block; width: 68px; height: 26px; border-radius: 12px; background-color:#526069; overflow: hidden; } .bg:after{ position: absolute; top:8px; left:0; display: block; content:''; width: 26px; height: 26px; background-color: #e6ebee; border-radius: 50%; transition:all 1s ease; background-image:-webkit-linear-gradient(0deg, #e5eaed, #fafbfb); } input{ display: none; } input:checked ~ label:after{ position: absolute; top:8px; left:56px; } input:checked ~label .switch{ width: 68px; } </style> <div class ="wrap"> <input type = "checkbox" id = "unchecked"/> <label for = "unchecked" class = "bg"> <div class = "switch"></div> </label> </div> </body> </html>
就這樣子啦~~~很簡單的,就是記錄一下這種思惟模式。