Home >Web Front-end >JS Tutorial >Native JS implementation method to determine collision (interesting example)
The following is the method I compiled for you to implement native JS to determine collisions. Interested students can take a look.
##HTML page code:
<div id="d1"></div> <div id="d2"></div>
CSS page code:
<style type="text/css"> * { padding: 0px; margin: 0px; } #d1{ width: 100px; height: 100px; background: red; position: absolute; } #d2{ width: 200px; height: 200px; background: yellow; position: absolute; top: 200px; left: 400px; position: absolute; } </style>JS page code:
<script type="text/javascript"> div=document.querySelectorAll("div"); function hit(obj){ obj.onmousedown=function(e){ var e=e||window.event; var dX=e.offsetX; var dY=e.offsetY; document.onmousemove=function(e){ var x=e.clientX; var y=e.clientY; obj.style.left=x-dX+"px"; obj.style.top=y-dY+"px"; if(div[0].offsetTop+div[0].offsetHeight>=div[1].offsetTop && div[0].offsetTop<=div[1].offsetTop+div[1].offsetHeight && div[0].offsetLeft+div[0].offsetWidth>=div[1].offsetLeft && div[0].offsetLeft<=div[1].offsetLeft+div[1].offsetWidth){ console.log("你撞我了!再撞一个试试!") }; } document.onmouseup=function(){ document.onmousemove=null; } } } hit(div[0]); hit(div[1]); </script>
The above is what I compiled I will give you a method to determine collisions in your native JS. I hope it will be helpful to you in the future. Related articles:
Simple operation of JS download file stream (code attached)
Generate verification code in js and verify (Contains code, simple and crude, teaching and training included)
About simple calls to obtain JSON data in JS (code attached, simple and crude)
The above is the detailed content of Native JS implementation method to determine collision (interesting example). For more information, please follow other related articles on the PHP Chinese website!