这里其实是遇到了一个案例,就是打蚊子的案例。
我们通过将瞄准的拍子拖动到蚊子身上,然后蚊子就会消失。

<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
html,body {
height: 100%;
width: 100%;
}
.box {
position: absolute;
height: 50px;
width: 50px;
background: red;
z-index: 1;
}
.movebox {
position: absolute;
height: 50px;
width: 50px;
background: red;
}
</style>
</head>
<body>
<div class="box"></div>
<div class="movebox box1">
 
</div>
<div class="movebox box4">
 
</div>
<div class="movebox box3">
 
</div>
<div class="movebox box2">
 
</div>
<div class="movebox box5">
 
</div>
<div class="movebox box6">
 
</div>
<script type="text/javascript">
const box = document.querySelector('.box');
let maxwidth = document.body.clientWidth - box.offsetWidth;
let maxheight = document.body.clientHeight - box.offsetHeight;
box.addEventListener('touchstart',function(e){
startx = e.touches[0].clientX - box.offsetLeft;
starty = e.touches[0].clientY - box.offsetTop;
document.addEventListener("touchmove", defaultEvent, { passive: false });
})
box.addEventListener('touchmove',function(e){
endx = e.touches[0].clientX - startx;
endy = e.touches[0].clientY - starty;
if (endx < 0){
endx = 0;
}
if(endy<0){
endy = 0;
}
if(endx > maxwidth){
endx = maxwidth;
}
if(endy >maxheight){
endy = maxheight;
}
box.style.left=endx+'px';
box.style.top=endy+'px'
console.log(diffnumleft<10&&diffnumleft>=0&&diffnumtop>-10&&diffnumtop<=0)
})
box.addEventListener('touchend',defaultEvent,{ passive: false });
function defaultEvent(e) {
e.preventDefault();
}
 
 
const movebox = document.querySelectorAll('.movebox');
setInterval(()=>{
movebox[0].style.left = (maxwidth - movebox[0].offsetLeft)*Math.random()+'px';
movebox[0].style.top = (maxheight - movebox[0].offsetHeight)*Math.random()+'px';
movebox[0].style.transition = 'all 1s'
},1000)
let diffnumleft = parseInt(box.style.left)-parseInt(movebox[0].style.left);
let diffnumtop = parseInt(box.style.top)-parseInt(movebox[0].style.top);
if(diffnumleft<10&&diffnumleft>=0&&diffnumtop<10&&diffnumtop>=0){
console.log(1)
}
</script>
</body>
</html>

这里我遇到了一个小问题,就是我移动后的判断,一直是false(就是移动的判断),后来将判断值输出了一下,发现这里一直是NaN。
然后将每个值都在console的面板里输出了一下,发现有的值是xxxpx,难怪会NaN,那么我这里就用parseint将值转化成数字即可,之所以可以用parseint,是因为他遇到遇到字母的话,会返回前面遇到的数字,那么我们的xxpx就会返回xx了,再之后判断就对了。

然后再就是要将判断写在touchmove里,因为我们要每一次移动都进行判断,如果写在外面那么肯定是不可能成功的。

这个可以看我的GitHub上,有一个比较成熟的案例。
https://github.com/datehoer/shengsai/tree/master/打蚊子

最后修改:2021 年 11 月 03 日 05 : 09 PM
如果觉得我的文章对你有用,请随意赞赏