当前位置: 首页 > 工具软件 > 变色方块 > 使用案例 >

JS拖拽事件,碰撞检测(碰撞变色效果)

百里业
2023-12-01
<html>
    <head>
        <meta charset="utf-8" />
        <title>碰撞检测</title>
        <style>
            .box {
                width:100px;
                height:100px;
                background:red;
                position:absolute;
            }
            .box1 {
                width:200px;
                height:200px;
                background:yellow;
                position:absolute;
                top:50%;
                left:50%;
                margin-top:-100px;
                margin-left:-100px;
            }
        </style>
    </head>
    <body onkeydown="show()">
        <div class="box1"></div>
        <div class="box"></div>
    </body>
      <script>
    window.onload = function() {
     var box = document.getElementsByClassName("box")[0];
     var box1 = document.getElementsByClassName("box1")[0];

     box.onmousedown = function(ev) {
         var ev = window.event || ev;
         var left = ev.clientX - box.offsetLeft;
         var top = ev.clientY - box.offsetTop;
         if (box.setCapture) {
             box.setCapture();
         }

         document.onmousemove = function() {
             var ev = window.event || ev;
             box.style.left = ev.clientX - left + "px";
             box.style.top = ev.clientY - top + "px";

             //获取运动div的left和top
             var l = ev.clientX - left;
             var t = ev.clientY - top;

             //获取参考div的left和top值
             var L = box1.offsetLeft;
             var T = box1.offsetTop;

             if (l + box.offsetWidth < L || t + box.offsetHeight < T || L + box1.offsetWidth < l || T + box1.offsetHeight < t) {
                 box1.style.background = "";
             } else {
                 box1.style["background"] = "orange";
             }

         }
         box.onmouseup = function() {
             document.onmousemove = box.onmouseup = "";
             if (box.releaseCapture) {
                 box.releaseCapture();
             }
         }
         return false;
     }
 }
      </script>
</html>
 类似资料: