代码改变世界

Javascript 创建一个动画元件的代码

2012-07-06 11:33  chris-shao  阅读(181)  评论(0编辑  收藏  举报
var DHTMLSprite =function(params)
{
    var width=params.width,
    height=params.height,
    imagesWidth=params.imagesWidth,
    $element=params.$drawTarget.append("<div/>").find(':last'),
    elementStyle=$element[0].style,
    mathFloor=Math.floor;
    $element.css({
        position:'absolute',
        width:width,
        height:height,
        backgroundImage:'url('+params.images+')'
    });
    var that={
        draw:function(x,y){
                elementStyle.left=x+'px';
                elementStyle.top=y+'px';
                return this;
        },
        changeImage:function(index){
                index *=width;
                var vOffset=-mathFloor(index/imagesWidth)*height;
                var hOffset=-index%imagesWidth;
                elementStyle.backgroundPosition=hOffset+'px '+vOffset+'px';
                return this;
        },
        show:function(){
            elementStyle.display='block';
            return this;
        },
        hide:function(){
            elementStyle.display='none';
            return this;
        },
        destory:function(){
            $element.remove();
        }
    }
return that;
}
var img =DHTMLSprite ({width:80,height:80,imagesWidth:330,$drawTarget:$("#group_nav"),images:'http://1812.img.pp.sohu.com.cn/images/2012/7/6/9/26/e33569437_1391c97fcacg213_b.jpg'}).draw(100,100).show();
var index=0;
var timer=function(){
if(index<20)
{
    console.warn(index);
    img.changeImage(index);
    index++;
    setTimeout(timer,20);
}else
{
        img.hide();
        img.destory();
}
}
timer();