JS实现拖拽元素时与另一元素碰撞检测

时间:2022-01-21 04:40:19

本文给大家分享一个用原生JS实现拖拽元素时与另个一元素碰撞检测的小Demo,效果如下:

JS实现拖拽元素时与另一元素碰撞检测

实现代码如下, 欢迎大家复制粘贴。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<!DOCTYPE html>
<html>
 
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>原生JS实现拖拽元素时与另个一元素碰撞检测</title>
  <style>
    #div1 {
      width: 100px;
      height: 100px;
      background: red;
      position: absolute;
      z-index: 2;
    }
 
    #div2 {
      width: 100px;
      height: 100px;
      background: yellow;
      position: absolute;
      left: 230px;
      top: 220px;
      z-index: 1;
    }
  </style>
  <script>
    window.onload = function () {
      var oDiv = document.getElementById('div1');
      var oDiv2 = document.getElementById('div2');
      // 鼠标按下时
      oDiv.onmousedown = function (ev) {
 
        var oEvent = ev || event;
        var disX = oEvent.clientX - oDiv.offsetLeft;
        var disY = oEvent.clientY - oDiv.offsetTop;
        // 鼠标移动时
        document.onmousemove = function (ev) {
 
          var oEvent = ev || event;
 
          oDiv.style.left = oEvent.clientX - disX + 'px';
          oDiv.style.top = oEvent.clientY - disY + 'px';
 
          var l1 = oDiv.offsetLeft;
          var r1 = oDiv.offsetLeft + oDiv.offsetWidth;
          var t1 = oDiv.offsetTop;
          var b1 = oDiv.offsetTop + oDiv.offsetHeight;
 
          var l2 = oDiv2.offsetLeft;
          var r2 = oDiv2.offsetLeft + oDiv2.offsetWidth;
          var t2 = oDiv2.offsetTop;
          var b2 = oDiv2.offsetTop + oDiv2.offsetHeight;
 
          // 碰撞检测的规则
          if (r1 < l2 || l1 > r2 || b1 < t2 || t1 > b2) {
            // 如果没有碰到
            oDiv2.style.background = 'yellow';
 
          } else {
            // 如果碰到了
            oDiv2.style.background = 'green';
          }
        };
        // 鼠标抬起时
        document.onmouseup = function () {
 
          document.onmousemove = null;
          document.onmouseup = null;
        };
      };
    };
  </script>
</head>
 
<body>
  <div id="div1"></div>
  <div id="div2"></div>
</body>
 
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。 

原文链接:https://blog.csdn.net/weixin_40629244/article/details/99670724