先看例子
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效果完成滾動切換。
1 @-webkit-keyframes scrollText2 { 2 0%{ 3 -webkit-transform: translateX(0px); 4 } 5 20%{ 6 -webkit-transform: translateX(-204px); 7 } 8 40%{ 9 -webkit-transform: translateX(-408px); 10 } 11 60%{ 12 -webkit-transform: translateX(-612px); 13 } 14 80%{ 15 -webkit-transform: translateX(-816px); 16 } 17 100%{ 18 -webkit-transform: translateX(-1020px); 19 } 20 } 21 @keyframes scrollText2 { 22 0%{ 23 transform: translateX(0px); 24 } 25 20%{ 26 transform: translateX(-204px); 27 } 28 40%{ 29 transform: translateX(-408px); 30 } 31 60%{ 32 transform: translateX(-612px); 33 } 34 80%{ 35 transform: translateX(-816px); 36 } 37 100%{ 38 transform: translateX(-1020px); 39 } 40 } 41 42 .box4{ 43 position: absolute; 44 top: 100px; 45 left: 100px; 46 width: 200px; 47 height: 30px; 48 overflow: hidden; 49 } 50 .border4{ 51 position: absolute; 52 top: 0px; 53 left: 0px; 54 width: 1400px; 55 -webkit-animation:scrollText2 12s infinite cubic-bezier(1,0,0.5,0) ; 56 animation:scrollText2 12s infinite cubic-bezier(1,0,0.5,0) ; 57 } 58 .border4 div{ 59 height: 30px; 60 width: 200px; 61 overflow: hidden; 62 display: inline-block; 63 } 64 .border4:hover{ 65 animation-play-state:paused; 66 -webkit-animation-play-state:paused; 67 }
CSS代碼說明:
- @-webkit-keyframes及@keyframes定義了從0% ~ 100%之間,每過20%的時間,向左移動204px,總共有6次移動;
- .box4 定義外容器的基本屬性
- .border4 定義了內容器的屬性,-webkit-animation:scrollText1 12s infinite cubic-bezier(1,0,0.5,0) 和 animation:scrollText1 12s infinite cubic-bezier(1,0,0.5,0) 定義了用12s種循環一次,無限循環的效果;
- .border4 div 定義了縱向滾動內容的基本樣式;
- .border4:hover 定義了鼠標移入容器時的效果,animation-play-state:paused 及 -webkit-animation-play-state:paused 定義了動畫暫停;
1 <div class="box4"> 2 <div class="border4"> 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條信息制作一個替代方法,在第一次循環結束后,可以無縫繼續滾動。