一、展示效果图
1、小男孩走路
2、一堆小男孩跑动
二、项目需求
1.图片
图片如下(背景透明):
2.代码
(1)小男孩走路:
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
#a_box{
width: 200px;
height: 356px;
background:url(img/boy.png) no-repeat ;
background-position: 0px 0px;
position: absolute;
left: 30px;
top: 30px;
}
</style>
</head>
<body>
<div id="a_box"></div>
<script type="text/javascript">
var box=document.getElementById("a_box");
var index=0;
var nowleft=30;
setInterval(function(){
index++;
if(index>3) index=0;
nowleft+=5;
a_box.style.left=nowleft+'px';
a_box.style.backgroundPosition=-200*index+'px 0px';
},200);
</script>
</body>
(2)一堆小男孩跑动:
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
div{
width: 200px;
height: 356px;
background:url(img/boy.png) no-repeat;
background-position: 0px 0px;
position: absolute;
}
</style>
</head>
<body>
<script type="text/javascript">
function boy(left,top){
this.left=left;
this.top=top;
this.init=function(){//创建方法
this.dom=document.createElement('div');//创建div节点
document.body.appendChild(this.dom);//拼接到body
this.dom.style.left=this.left+'px';
this.dom.style.top=this.top+'px';
}
this.move=function(){//移动方法
var index=0;
var self=this;//因为在setInterval内this是window的对象,所以要在setInterval外部备份this
this.timer=setInterval(function(){
index++;//图片索引++
if(index>3) index=0;//四张小图切换
self.left+=5;
if(self.left>=280) self.die();//当小男孩走到x米处时,自动销毁小男孩
//设置位置
self.dom.style.left=self.left+'px';
self.dom.style.backgroundPosition=-200*index+'px 0px';
},100);
}
this.die=function(){//销毁方法
clearInterval(this.timer);//停止
document.body.removeChild(this.dom);//移除节点
}
this.init();//调用
this.move();//调用
}
setInterval(function(){//定时器
new boy(100,parseInt(Math.random()*500));
},1000);
</script>
</body>
三、结语
加油!小伙伴们!有问题都可以留言咨询哦!