超陋的小方块移动小游戏(鼠标触碰小方块,小方块会沿其他三个方向逃避鼠标的触碰)
作者:互联网
超陋的代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>实现小方块随机移动小游戏</title>
<style>
*{
margin: 0;
padding: 0;
}
html,body{
width: 100%;
height: 100%;
background-color: thistle;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
</style>
</head>
<body>
<h3>调皮的小方块</h3>(鼠标触碰小方块,小方块会逃离)
<div style="width: 900px;height: 500px;border: 1px solid black;background-color: aliceblue;">
<div style="width: 50px;height: 50px;background-color:lightcoral;position: absolute;left: 300px;top: 200px">
<div style="width: 50px;height: 2px;position:absolute;top: 0px;"></div>
<div style="width: 50px;height: 2px;position: absolute;bottom: 0;"></div>
<div style="width: 2px;height: 50px;position: absolute;left: 0;"></div>
<div style="width: 2px;height: 50px;position: absolute;right: 0;top: 0;"></div>
</div>
</div>
<script>
var div = document.getElementsByTagName('div')[1];
var divs = document.getElementsByTagName('div');
var num,nums;
div.onmouseover = function(e){
for(var i = 2;i < 6;i ++){
(function(i){
divs[i].onmouseover = function(){
num = i;
}
}(i))
}
if(num == 2){
nums = Math.random() - 0.5;
if(nums >= 0){
div.style.left = parseInt(div.style.left) + (Math.random() - 0.5) * 100 + 'px';
}else{
div.style.top = parseInt(div.style.top) + Math.random() * 50 + 'px';
}
}if(num == 3){
nums = Math.random() - 0.5;
if(nums >= 0){
div.style.left = parseInt(div.style.left) + (Math.random() - 0.5) * 100 + 'px';
}else{
div.style.top = parseInt(div.style.top) - Math.random() * 50 + 'px';
}
}if(num == 4){
nums = Math.random() - 0.5;
if(nums >= 0){
div.style.left = parseInt(div.style.left) + Math.random() * 50 + 'px';
}else{
div.style.top = parseInt(div.style.top) + (Math.random() - 0.5) * 100 + 'px';
}
}if(num == 5){
nums = Math.random() - 0.5;
if(nums >= 0){
div.style.left = parseInt(div.style.left) - Math.random() * 50 + 'px';
}else{
div.style.top = parseInt(div.style.top) + (Math.random() - 0.5) * 100 + 'px';
}
}
}
</script>
</body>
</html>
本来在网上看到了一个判断鼠标从哪个方向移入小方块的一个原生JS小算法程序,奈何我太菜了,没看懂,所以出此下策:在小方块里用四个div来变向监听鼠标的移入方向,,,,自己感觉特别特别差的一个代码 ,毫无任何布局,逻辑,仅仅只是把小实现的现象完成了。(JS皮毛都还没了解完,就先这样吧–>不过我这个对于和我一样的初学者来说应该还蛮好理解的,哈哈哈哈哈哈)
标签:触碰,style,鼠标,nums,小方块,random,div,Math 来源: https://blog.csdn.net/weixin_46102597/article/details/106445279