在一些網頁中,我們會看到有一行或多行文字向上滾動,就像輪播一樣。那我們如何實現它呢,現在就開始吧!
單行文字
html代碼
<div id="scrollDiv">
<ul>
<li>百度 www.baidu.com</li>
<li>腳本之家 www.jb51.net</li>
<li>這是公告標題的第三行</li>
<li>這是公告標題的第四行</li>
<li>這是公告標題的第五行</li>
<li>這是公告標題的第六行</li>
<li>這是公告標題的第七行</li>
<li>這是公告標題的第八行</li>
</ul>
</div>
css樣式
<style> *{margin:0; padding:0;} #scrollDiv{width: 500px; height: 25px; line-height: 25px;/*這里的height是25px*/
margin:50px auto; overflow:hidden;} #scrollDiv li{height:25px; cursor:pointer;} </style>
jQuery程序
<script src="jquery-1.11.3.js"></script>
<script>
function autoscroll(obj){
//這里的25px是#scrollDiv的高度
$(obj).find("ul:first").animate({marginTop:"-25px"},1000,function(){
$(this).css("marginTop","0px").find("li:first").appendTo(this)
})/*$(this).css("marginTop","0px")這里也許會有人搞不明白,為什么又設為0。因為在ul向上移25px的時候,其第一個li會添加到ul的末尾,如果ul的marginTop不設為0的話,整個ul就會慢慢移出它的父盒子,最后使得它的父盒子變空,實現不了原本想要實現的效果。*/
}
$(document).ready(function(){
setInterval('autoscroll("#scrollDiv")',1500)
})
</script>
多行文字
這里的html代碼同上
css樣式
<style> *{margin:0; padding:0;} #scrollDiv{width: 500px; height: 100px; line-height: 25px;
margin:50px auto; overflow:hidden;}/*這里的height是100px*/ #scrollDiv li{height:25px; cursor:pointer;} </style>
jQuery程序
<script src="jquery-1.11.3.js"></script>
<script>
function autoscroll(obj){ $(obj).find("ul:first").animate({marginTop:"-100px"},500,function(){ var str=$(this).css("marginTop","0px") for(var i=0;i<4;i++){/*這里的for循環目的是讓ul里的前四個li一起添加到ul的末尾,
實現多行文字滾動。i可以根據實際需要而定。*/ str.find("li:first").appendTo(this) } }) } $(document).ready(function(){ setInterval('autoscroll("#scrollDiv")',1500) }) </script>
