<style>
*{
margin: 0;
padding: 0;
}
.girl{
width:150px;
height: 80px;
background: url("girl.png") no-repeat 0 -673px;
position: absolute;
left: 0;
top: 100px;
}
#box::after{
content: "";
display: block;
visibility: hidden;
clear: both;
}
button{
width: 200px;
height: 60px;
border: none;
outline: none;
background-color: skyblue;
line-height: 60px;
text-align: center;
position: fixed;
left: 100px;
top: 500px;
font-size: 30px;
border-radius: 6px;
}
</style>
<body>
<button onclick = "javascript:new Girl()">创建女孩</button>
<div id="box">
</div>
</body>
</html>
<script>
function Girl() {
//初始化left值
this.left = 0;
//初始化速度 1-10
this.speed = parseInt(Math.random() * 10) + 1;
//不同女孩的top值
this.top = parseInt(Math.random() * 4 );
//图片的步伐 0-7 8个步伐图
this.step = 0;
//dom 初始化
this.init()
//把小女孩统一管理到一个数组
GirlArr.push(this);
}
Girl.prototype.init = function () {
//创建一个dom
this.dom = document.createElement("div");
//添加类名
this.dom.className = 'girl';
//设置不同图top
this.dom.style.top = (this.top * 100) + "px";
//dom上树
document.getElementById("box").appendChild(this.dom);
}
Girl.prototype.go = function () {
//设置移动距离
this.left += this.speed;
//别让走太远大于800删除
if(this.left>800)this.temoveDom();
this.dom.style.left = this.left + "px";
//设置移动步伐
this.step ++;
this.step = this.step>7? 0 : this.step;
this.dom.style.backgroundPosition = -255 * this.step + "px -673px";
}
Girl.prototype.temoveDom = function () {
//让父元素删除子元素
document.getElementById("box").removeChild(this.dom);
//dom从数组中也需要删除
for(var i=GirlArr.length - 1;i>=0;i--){
if(GirlArr[i] === this){
GirlArr.splice(i,1)
}
}
}
//把所有的女孩放到一个数组里
var GirlArr = []
setInterval(() => {
for(var i=0;i<GirlArr.length;i++){
GirlArr[i].go();
}
}, 100);
</script>