这里没有办法展示动态效果,具体动态效果请复制到浏览器并在浏览器控制台上查看具体效果:
CSS部分:
<style> * { margin: 0; padding: 0; } div { position: absolute; top: 0; left: 0; border-radius: 50% } #div1 { width: 200px; height: 200px; background: green } #div2 { width: 100px; height: 100px; background: red } </style>
HTML部分:
<body> <div id="div1"></div> <div id="div2"></div> </body>
js部分:
<script> const div1 = document.getElementById("div1"); const div2 = document.getElementById("div2"); function move(domElement) { domElement.onmousedown = function (e) { const mouseX = e.clientX, mouseY = e.clientY, oldLeft = domElement.offsetLeft, oldTop = domElement.offsetTop document.onmousemove = function (e) { const x = e.clientX, y = e.clientY domElement.style.left = oldLeft + (x - mouseX) + 'px' domElement.style.top = oldTop + (y - mouseY) + 'px' } document.onmouseup = function () { document.onmousemove = null } } } move(div1) move(div2) setInterval(function () { const x = div1.offsetWidth / 2 + div1.offsetLeft //div1的圆心left值 const x2 = div2.offsetWidth / 2 + div2.offsetLeft //div2的圆心left值 const y = div1.offsetWidth / 2 + div1.offsetTop //div1的圆心top值 const y2 = div2.offsetWidth / 2 + div2.offsetTop //div2的圆心top值 const circleDistance = Math.pow(x - x2, 2) + Math.pow(y - y2, 2) //斜边的平方 const r1AndR2 = Math.pow(div1.offsetWidth / 2 + div2.offsetWidth / 2, 2) if (circleDistance <= r1AndR2) { console.log('撞上了') } }, 30) </script>
标签:const,domElement,碰撞,源码,测试,document,offsetWidth,div2,div1 From: https://www.cnblogs.com/xm11667799/p/17519017.html