碰撞练习

一:碰撞练习的css部分:

<style>

* {

padding: 0;

margin: 0;

}

#wrap {

width: 400px;

height: 200px;

/*margin: 0 auto;

margin-top: 100px;*/

border: 1px solid red;

position: relative;

}

#bird {

width: 20px;

height: 20px;

position: absolute;

background-color: red;

}

</style>

二:碰撞练习的Html部分

<body>

<div id="wrap">

<div id="bird"></div>

</div>


</body>

三:碰撞练习的js部分

<script type="text/javascript">

var wrap = document.getElementById("wrap");

var bird = document.getElementById("bird");

var arrA = [];


function randomNum(m, n) {

return Math.floor(Math.random() * (n - m) + m);

}


function randomtree(m) {

for (var i = 0; i < m; i++) {

var div1 = document.createElement("div");

div1.style.width = "50px";

div1.style.height = randomNum(50, 80) + "px";

div1.style.backgroundColor = "greenyellow";

div1.style.position = "absolute";

div1.style.left = "80px";

if(i%2==0){

div1.style.top = "0px";

}else{

div1.style.bottom = "0px";

}

wrap.appendChild(div1);

arrA.push(div1);

}

console.log(arrA);

}

randomtree(2);

bird.onmousedown = function(e) {

document.onmousemove = function() {

var event1 = event || e;

bird.style.left = event1.clientX - 10 + "px";

bird.style.top = event1.clientY - 10 + "px";

//判断是否碰到上面的柱子

if (bird.offsetLeft > (arrA[0].offsetLeft +arrA[0].offsetWidth) || bird.offsetLeft+bird.offsetWidth < arrA[0].offsetLeft) 

{

console.log("正常");

arrA[0].style.backgroundColor = "greenyellow";

} else if (bird.offsetTop > (arrA[0].offsetTop + arrA[0].offsetHeight)) 

{

console.log("正常");

arrA[0].style.backgroundColor = "greenyellow";

} else {

arrA[0].style.backgroundColor = "red";

}

//判断是否碰到下面的柱子

if (bird.offsetLeft > (arrA[1].offsetLeft + arrA[1].offsetWidth) || bird.offsetLeft+bird.offsetWidth < arrA[1].offsetLeft) 

{

console.log("正常");

arrA[1].style.backgroundColor = "greenyellow";

} else if (bird.offsetTop+bird.offsetHeight<arrA[1].offsetTop) 

{

console.log("正常");

arrA[1].style.backgroundColor = "greenyellow";

} else {

arrA[1].style.backgroundColor = "red";

}

}

}

bird.onmouseup = function(e) {

document.onmousemove = "";

arrA[0].style.backgroundColor = "greenyellow";

}

</script>


</html>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值