Javascript中的碰壁反弹

初次学习这方面,有不足之处请多指教。

做了一个小球碰到墙壁就会反弹,变色的一个小的程序。
关于HTML文件就不做多余的描述,就是一个大盒子里面包含一个小球。
下面着重列举css样式与js代码;

CSS样式:

@charset "utf-8";

body {
    margin: 0 auto;
    position: relative;
}

.container {
    margin:0 auto;
    width: 600px;
    height: 400px;
    position: relative;
    border: solid 1px #ccc;
}

.container div {
    width: 100px;
    height: 100px;
    overflow: hidden;
    border-radius: 50%;
    position: absolute;
}
.container div:nth-child(2) {
    background-color: green;
    top: 0px;
    right: 0px;
}

JS代码:

function main() {
    var _lists = document.getElementsByTagName("div")[0].getElementsByTagName("div");
    var _timer = 0;
    var _height = 400;
    var _width = 600;
    var _left1 = _width - 100;
    var _top1 = 0;
    var _h1 = 0, _v1 = 0;
    (function move() {
        window.clearTimeout(_timer);
        if ((_lists[0].offsetLeft - _lists[1].offsetLeft) * (_lists[0].offsetLeft - _lists[1].offsetLeft) + (_lists[0].offsetTop - _lists[1].offsetTop) * (_lists[0].offsetTop - _lists[1].offsetTop) < 10000) {
            _h1 = _h1 ? 0 : 1;
        }
        if (_h1 == 0) {
            _left1 -= 10;
            if (_left1 <= 0) {
                _left1 = 0;
                _h1 = 1;
                _lists[1].style.background="pink";
            }
        } else {
            _left1 += 10;
            if (_left1 >= _width - 100) {
            
                _left1 = _width - 100;
                _h1 = 0;
                _lists[1].style.background="red";
            }
        }
        if (_v1 == 0) {
            _top1 += 5;
            if (_top1 >= _height - 100) {
               
                _lists[1].style.background="black";
                _top1 = _height - 100;
                _v1 = 1;
            }
        } else {
            _top1 -= 5;
            if (_top1 <= 0) {
                _top1 = 0;
                _v1 = 0;
                _lists[1].style.background="yellow";
            }
        }
        
        _lists[1].style.left = _left1 + "px";
        _lists[1].style.top = _top1 + "px";
        _timer = window.setTimeout(move, 30);

    })();
}


window.onload = function () {
    main();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值