文章出處
文章列表
JS實現
最近做項目的時候需要實現一個字符逐個出現的打字效果,在網上一搜有個不錯的jQuery插件Typed.js,效果很贊
<div class="element"></div>
<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();
CSS實現
如果對細節和瀏覽器兼容性要求的不是很嚴格,我們可以通過CSS3實現
animation-timing-function
CSS3的動畫都接觸過,我們平時這么用
animation: animation-name animation-duration animation-iteration-count
animation: 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])
number_of_steps
動畫分為多少步執行direction
動畫顯示狀態,end:默認值,第一幀開始前顯示,start:第一幀結束后顯示
看個科學的圖片幫助理解
走兩步
有了這些我們就能做個好玩兒的效果了
.walk {
width: 125px;
height: 150px;
background: url(http://lsly1989.qiniudn.com/xxxasddbgfbwalk.jpg) 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;}
}
參考
MDN: timing-function
文章列表
全站熱搜