CSS 實現打字效果

來源:互聯網
上載者:User

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參數很多,也可以寫成分別的屬性

  1. animation-name

  2. animation-duration

  3. animation-timing-function

  4. animation-delay

  5. animation-iteration-count

  6. animation-direction

今天我們就要關注一下animation-timing-function,大多數動畫在時間軸上時線性變化的,jQuery動畫的時候我們用的liner參數就是這意思,但CSS3提供了一些其它的變化方式由animation-timing-function屬性指定

  1. ease

  2. linear

  3. ease-in

  4. ease-out

  5. ease-in-out

  6. step-start

  7. step-end

  8. steps

  9. cubic-bezier

每種動畫效果都可以對應一種貝茲路徑 cubic-bezier可以幫我直觀的看一下貝茲路徑效果,這裡不多說了

steps

我們看一下steps的效果,其實顧名思義就可以想到steps什麼意思,就像俄羅斯方塊的小格子往下掉也是動畫,但是不是連續的,更像是逐幀的,steps就是實現這種效果的

steps的文法

steps(number_of_steps, [start|end])
  • number_of_steps 動畫分為多少步執行

  • direction 動畫顯示狀態,end:預設值,第一幀開始前顯示,start:第一幀結束後顯示

看個科學的圖片協助理解

走兩步

有了這些我們就能做個好玩兒的效果了

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.