You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript实现两个矩形鼠标拖拽碰撞检测功能失效问题咨询

你代码中存在的问题:

  • 拼写错误:getBoundingClientRect() 返回的元素宽度属性是 width,你代码里全部写成了 weight,直接导致碰撞判断的数值完全错误
  • 变量未定义:你已经用变量 el2 选中了绿色矩形元素,但碰撞触发的逻辑里直接使用了未声明的 item2 变量,浏览器控制台会抛出引用错误,逻辑直接中断不执行
  • 样式修改无效:你给 item2 修改的是 color 属性(文字颜色),但绿色矩形内没有任何文本内容,就算逻辑触发了也看不到效果,建议改成修改背景色等可见属性
  • 逻辑优化点:你只在页面初始化时获取了一次绿色矩形的位置 rect2,如果后续绿色矩形位置会发生变化,碰撞判断就会失效,建议每次执行碰撞逻辑前重新获取一次 rect2 更稳妥

修正后的JavaScript代码:

const el1 = document.querySelector(".item1");
const el2 = document.querySelector(".item2");
var rect1,rect2;
// 固定位置的话这里一次获取也可以,动态位置就移到mousemove里
rect2 = el2.getBoundingClientRect();
el1.addEventListener("mousedown", mousedown);

function mousedown(e) {
  window.addEventListener("mousemove", mousemove);
  window.addEventListener("mouseup", mouseup);

  let prevX = e.clientX;
  let prevY = e.clientY;

  function mousemove(e) {
    let newX = prevX - e.clientX;
    let newY = prevY - e.clientY;

    rect1 = el1.getBoundingClientRect();

    el1.style.left = rect1.left - newX + "px";
    el1.style.top = rect1.top - newY + "px";

    prevX = e.clientX;
    prevY = e.clientY;
    // 修正碰撞逻辑
    if (rect1.left < rect2.left + rect2.width &&
      rect1.left + rect1.width > rect2.left &&
      rect1.top < rect2.top + rect2.height &&
      rect1.height + rect1.top > rect2.top) {
      // 修改变量和修改的样式属性
      el2.style.background = "#FF0006";
    } else {
      // 离开碰撞范围后恢复绿色,可选逻辑
      el2.style.background = "green";
    }
  }

  function mouseup() {
    window.removeEventListener("mousemove", mousemove);
    window.removeEventListener("mouseup", mouseup);
  }
}

内容的提问来源于stack exchange,提问作者fast539

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 21:54:03