一:碰撞练习的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>
791

被折叠的 条评论
为什么被折叠?



