行走的女神--面向对象--数组的统一管理和定时器操作

<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>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值