小方块删除不掉
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
main {
width: 500px;
height: 600px;
background: #aaffff;
position: relative;
}
#box1 {
position: absolute;
top: 150px;
left: 250px;
width: 20px;
height: 20px;
background: black;
}
</style>
</head>
<body>
<main>
<div id="box1"></div>
</main>
<script type="text/javascript">
let aMain = document.getElementsByTagName('main')
let aDiv = aMain[0].getElementsByTagName('div')
for (let i = 0; i < aDiv.length; i++) {
// 生成一个方块
if (aDiv.length == 1) {
let oDiv = document.createElement('div');
aMain[0].appendChild(oDiv);
oDiv.style.width = 20 + "px"
oDiv.style.height = 20 + "px"
oDiv.style.position = 'absolute'
oDiv.style.background = 'black'
oDiv.style.top = Math.random() * 300 + 'px'
oDiv.style.left = Math.random() * 300 + 'px'
}
// 获取新增方块位置
let a = aDiv[1].offsetTop
let b = aDiv[1].offsetLeft
if (aDiv.length == 2) {
// 移动小方块
document.onkeydown = function(e) {
if (e.keyCode == 65 || e.keyCode == 37) {
aDiv[0].style.left = aDiv[0].offsetLeft - 10 + 'px'
} else if (e.keyCode == 87 || e.keyCode == 38) {
aDiv[0].style.top = aDiv[0].offsetTop - 10 + 'px'
} else if (e.keyCode == 68 || e.keyCode == 39) {
aDiv[0].style.left = aDiv[0].offsetLeft + 10 + 'px'
} else if (e.keyCode == 83 || e.keyCode == 40) {
aDiv[0].style.top = aDiv[0].offsetTop + 10 + 'px'
}
// 计算两方块的距离
let TopDce = Math.abs(aDiv[0].offsetTop - a)
let LeftDce = Math.abs(aDiv[0].offsetLeft - b)
// 如果贴近则删除一个方块
if (TopDce < 15 && LeftDce < 15) {
aMain[0].removeChild(aDiv[1])
aDiv[0].style.hight = aDiv[0].offsetHeight + 100 + 'px'
}
}
}
}
</script>
</body>
</html>