JS實現
最近做項目的時候需要實現一個字元逐個出現的打字效果,在網上一搜有個不錯的jQuery外掛程式Typed.js,效果很贊
<p class="element"></p><script src="typed.js"></script><script> $(function(){ $(".element").typed({ strings: ["First sentence.", "Second sentence."], typeSpeed: 0 }); });</script>
具體用法可以看看項目地址,帶注釋的源碼200多行,不算複雜
實現方法也不神奇,大多數人肯容易可以想到,用js逐個向容器內添加字元,作者做了很多字元的出來還有速度神馬的,我們可以擼一個簡單的
var s = 'Hello World! Hello World! Hello World!';var con = $('.container');var index = 0;var length = s.length;var tId = null;function start(){ con.text(''); tId=setInterval(function(){ con.append(s.charAt(index)); if(index++ === length){ clearInterval(tId); index = 0; start() } },100);}start();
JS Bin
CSS實現
如果對細節和瀏覽器安全色性要求的不是很嚴格,我們可以通過CSS3實現
animation-timing-function
CSS3的動畫都接觸過,我們平時這麼用
animation: animation-name animation-duration animation-iteration-countanimation: name 5s infinite;
其實完整版的animation參數很多,也可以寫成分別的屬性
-
animation-name
-
animation-duration
-
animation-timing-function
-
animation-delay
-
animation-iteration-count
-
animation-direction
今天我們就要關注一下animation-timing-function,大多數動畫在時間軸上時線性變化的,jQuery動畫的時候我們用的liner參數就是這意思,但CSS3提供了一些其它的變化方式由animation-timing-function屬性指定
-
ease
-
linear
-
ease-in
-
ease-out
-
ease-in-out
-
step-start
-
step-end
-
steps
-
cubic-bezier
每種動畫效果都可以對應一種貝茲路徑 cubic-bezier可以幫我直觀的看一下貝茲路徑效果,這裡不多說了
steps
我們看一下steps的效果,其實顧名思義就可以想到steps什麼意思,就像俄羅斯方塊的小格子往下掉也是動畫,但是不是連續的,更像是逐幀的,steps就是實現這種效果的
steps的文法
steps(number_of_steps, [start|end])
看個科學的圖片協助理解
走兩步
有了這些我們就能做個好玩兒的效果了
JS Bin
.walk { width: 125px; height: 150px; background: url(http://www.php.cn/) left; -webkit-animation:anima 1s steps(16) infinite ;}@-webkit-keyframes anima{ from { background-position:2000px 0;} to {background-position:0px 0;}}
打字效果
打字效果也就可想而知了,改變容器寬度即可(只能單行使用,還得做到每步增加長度和字母寬度一致,還是js好其實)
.typing{ width:250px; white-space:nowrap; overflow:hidden; -webkit-animation: type 3s steps(50, end) infinite; animation: type 3s steps(50, end) infinite;}@-webkit-keyframes type{ from { width: 0;}}@keyframes type{ from { width: 0;}}
JS Bin