老慣例,先看例子。
This is a test 1.
This is a test 2.
This is a test 3.
This is a test 4.
This is a test 5.
This is a test 1.
實現原理:
1. 利用CSS3的@keyframes規則創建動畫效果;
2. 使用CSS3的animation效果完成滾動切換。
CSS代碼
1 @-webkit-keyframes scrollText1 { 2 0%{ 3 -webkit-transform: translateY(0px); 4 } 5 20%{ 6 -webkit-transform: translateY(-30px); 7 } 8 40%{ 9 -webkit-transform: translateY(-60px); 10 } 11 60%{ 12 -webkit-transform: translateY(-90px); 13 } 14 80%{ 15 -webkit-transform: translateY(-120px); 16 } 17 100%{ 18 -webkit-transform: translateY(-150px); 19 } 20 } 21 22 @keyframes scrollText1 { 23 0%{ 24 transform: translateY(0px); 25 } 26 20%{ 27 transform: translateY(-30px); 28 } 29 40%{ 30 transform: translateY(-60px); 31 } 32 60%{ 33 transform: translateY(-90px); 34 } 35 80%{ 36 transform: translateY(-120px); 37 } 38 100%{ 39 transform: translateY(-150px); 40 } 41 } 42 43 .box3{ 44 position: relative; 45 top: 20px; 46 left: 20px; 47 width: 200px; 48 height: 30px; 49 overflow: hidden; 50 border:1px solid #ccc; 51 } 52 53 .border3{ 54 top: 0px; 55 -webkit-animation:scrollText1 8s infinite cubic-bezier(1,0,0.5,0) ; 56 animation:scrollText1 8s infinite cubic-bezier(1,0,0.5,0) ; 57 } 58 59 .border3 div{ 60 height: 30px; 61 } 62 63 .border3:hover{ 64 animation-play-state:paused; 65 -webkit-animation-play-state:paused; 66 }
CSS代碼說明:
- @-webkit-keyframes及@keyframes定義了從0% ~ 100%之間,每過20%的時間,向上移動30px,總共有6次移動;
- .box3 定義外容器的基本屬性
- .border3 定義了內容器的屬性,-webkit-animation:scrollText1 8s infinite cubic-bezier(1,0,0.5,0) 和 animation:scrollText1 8s infinite cubic-bezier(1,0,0.5,0) 定義了用8s種循環一次,無限循環已經移動是的效果;
- .border3 div 定義了縱向滾動內容的基本樣式;
- .border3:hover 定義了鼠標移入容器是的效果,animation-play-state:paused 及 -webkit-animation-play-state:paused 定義了動畫暫停;
HTML代碼
1 <div class="box3"> 2 <div class="border3"> 3 <div>This is a test 1.</div> 4 <div>This is a test 2.</div> 5 <div>This is a test 3.</div> 6 <div>This is a test 4.</div> 7 <div>This is a test 5.</div> 8 <div>This is a test 1.</div> 9 </div> 10 </div>
HTML代碼說明:
定義了6條信息可以縱向滾動,其中前5條是真正縱向滾動的信息,第6條和第1條信息是一樣的,原因很簡單,因為使用了@keyframes方式來實現動畫效果,第1條信息的效果是默認為停止的,所以用第6條信息制作一個替代方法,在第一次循環結束后,可以無縫繼續滾動,大家可以去掉第6條試一下,就可以看見效果了。
至此,大功告成。