標籤:
1.最佳化了之前的代碼;
2.修正了先前按照文字的條目的數量計算速度的問題,現在改為按照字元的個數計算動畫執行一次需要的時間,更為精確;
3.增添了每一行JS代碼的注釋。
4.這個案例的用途一般為警示資訊的展示:
警示的條數是不確定的,每條警示的字數是不確定的,展示警示的地區可根據瀏覽器的解析度進行放大縮小;
本案例的書寫滿足這幾個條件。
5.本案例的實現思路:
1)設定一個展示文字的div:該div的寬度用百分比來表示;
2)設定一個能夠放下所有的文字條目的div:該div的寬度通過計算得到;
3)擷取每一條文字資訊載入到父級div中,通過迴圈擷取到每一條資訊的寬度和字元個數,然後分別求和;
4)每一條資訊寬度求和得到其父級div的寬度,並將父級div的margin-left設定為其寬度的負數;而且動畫是從margin-right:100%開始的,這樣就完成了從右向左的動畫效果。
5)根據每條資訊的字元個數求和後計算出執行一次動畫所需的總時間。
<!doctype html><html><head><meta charset="utf-8"><title>無標題文檔</title><style>.scrollContainer{ width:50%; height:30px; line-height:30px; margin-top:10px; overflow:hidden; background-color:#333; } @-webkit-keyframes scroll{from {margin-left:100%;}}@-moz-keyframes scroll{from {margin-left:100%;}}@-ms-keyframes scroll{from {margin-left:100%;}}.scroll{ height:30px; overflow:hidden; -webkit-animation: scroll 5s linear 1s infinite; -moz-animation: scroll 5s linear 1s infinite; -ms-animation-name: scroll 5s linear 1s infinite; animation-name: scroll 5s linear 1s infinite; } .contentItem{ line-height:30px; float:left; padding-right:20px; box-sizing:border-box; font-size:18px; overflow:hidden; color:#E3FF00; text-decoration:none; } .scrollBox:hover{ -webkit-animation-play-state:paused; -moz-animation-play-state:paused; -ms-animation-play-state:paused; animation-play-state:paused; } </style><script src="jquery-1.11.3.min.js"></script></head><body> <div class="scrollContainer"> <div class="scrollBox" id="content"></div> </div> <script type="text/javascript"> $(document).ready(function(){ var newarry = ["This is the first item!","This is the second item!","This is the third item!","This is the fourth item!"];//需要展示的文字 var len = newarry.length;//擷取資料的條數 var wordLen = 0;//每條資料中的字元長度變數 var sum=0;//每條資料所佔寬度變數 $("#content").empty();//清空資料的父級 for(var i=0;i<len;i++){ var divStr = "<a class=‘contentItem‘ href=‘‘>"+newarry[i]+"</a>"; $("#content").append(divStr);//資料的父級內部插入第i條資料 var boxWidth=$(".contentItem").eq(i).width()+22; sum+=boxWidth;//求取所有資料的寬度的和 wordLen+=(newarry[i].length+2);//求取所有字元的個數,間距按照2個字元計算 }; if(len>0){ $(".scrollBox").css({"animation-duration":0.5+0.5*wordLen+"s"},{"-moz-animation-duration":0.5+0.5*wordLen+"s"},{"-webkit-animation-duration":0.5+0.5*wordLen+"s"}); };//設定動畫迴圈一次需要的總時間,每個字元為0.5s $(".scrollBox").width(sum); var width = $(".scrollBox").width(); $(".scrollBox").css({"marginLeft":-width});//設定資料父級的左邊界 $(".scrollBox").addClass("scroll");//添加動畫 }); </script></body></html>
css3 文字輪番滾動效果2——改進版