jQuery 平滑滚动

Posted on 2008-09-26 16:10  BingLiang Sha  阅读(1501)  评论(0编辑  收藏  举报
按照自己的思路,使用jQuery,根据实际需求写了一个内容平滑滚动框,当作学习jQuery的练习。代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style type="text/css">
ul
{
    margin
:0px;
    padding
:0px;
    list-style
:none;
}
ul li
{
    margin
:0px;
    padding
:0px;
    list-style
:none;
}
#scroll
{
    height
:120px;
    overflow
:hidden;
}
#scroll li
{
    height
:30px;
}
</style>
<script type="text/javascript" src="jq/jquery-1.2.6.js"></script>
<script>
jQuery(document).ready(
function(){
    
var moveStep=1;
    
//滚动初始值
    var step=0;
    
//是否需要滚动
    var canScroll=true;
    
var $scroll=$("#scroll");
    
//滚动框高度
    var containerHeight=$("#scroll").height();
    
var actualHeight=0;
    
var $li=$("#scroll >ul:first >li");
    
var totalItems=$li.length;    
    
var itemHeight=$li.eq(0).height();
    
//滚动内容总高
    var actualHeight=totalItems*itemHeight;
    
//内容框高度和滚动框高度的差值,用于重定位滚动内容
    var diff=actualHeight-containerHeight;
    
//不需要滚动
    if(diff<=0){
        canScroll
=false;
    }
    
function scroll(){
        
if(step>actualHeight){
            step
=1;    
        }
        step
+=moveStep;    
        
if(step<=0){
            step
=actualHeight;
        }    
        $scroll.scrollTop(step);
//jQuery1.2以上才支持scrollTop方法
    }
    
var interval;
    
if(canScroll){
        $(
"#scroll >ul:first").clone().appendTo("#scroll");
        interval
=setInterval(scroll,50);
    }
    $scroll.hover(
function(){
        clearInterval(interval);
    },
function(){
        interval
=setInterval(scroll,50);
    });
    $(
"#up").mousedown(function(){
        moveStep
=5;        
    }).mouseup(
function(){
        moveStep
=1;
    });
    
    $(
"#down").mousedown(function(){
        moveStep
=-5;
    }).mouseup(
function(){
        moveStep
=1;
    });
});
</script>
</head>

<body>
<img id="up" src="go_up.gif" />
<div id="scroll">
    
<ul>
        
<li>11111111</li>
        
<li>22222222</li>
        
<li>33333333</li>
        
<li>44444444</li>
        
<li>55555555</li>
        
<li>66666666</li>
        
<li>77777777</li>
    
</ul>
</div>
<img id="down" src="go_down.gif" />
</body>
</html>