元素跟随鼠标移动

**1、index.html

javascript 复制代码
<div id="wrap">
    <div class="box"></div>
    <div class="box"></div>
</div>

2、app.js

javascript 复制代码
let MOVE_DOM_CLASS = "box";
let wrap = document.querySelector("#wrap");
let w_left = getWrapPositon("offsetLeft");
let w_right = getWrapPositon("right");
let w_top = getWrapPositon("offsetTop");
let w_bottom = getWrapPositon("bottom");

// 获取外层的边框位置
function getWrapPositon(ps) {
  switch (ps) {
    case "offsetLeft":
      return wrap[ps];
      break;
    case "offsetTop":
      return wrap[ps];
      break;
    case "right":
      return wrap.clientWidth;
      break;
    case "bottom":
      return wrap.clientHeight;
      break;
    default:
      break;
  }
}

document.onmousedown = function (e) {
  mousedownEvent(e);
};

document.onmouseup = function (e) {
  mouseupEvent(e);
};

// 按下鼠标
function mousedownEvent(d_ev) {
  setDomStyle(d_ev, "add");
  document.onmousemove = function (m_ev) {
    setDomPostion(m_ev, d_ev);
  };
}

// 松开鼠标
function mouseupEvent(e) {
  setDomStyle(e, "remove");
  document.onmousemove = null;
}

// 处理 dom 样式
function setDomStyle(e, type) {
  let box = getTarget(e);
  box && box.classList[type]("box_bg");
}

// 设置 dom 位置
function setDomPostion(m_ev, d_ev) {
  const { x, y } = getPostion(m_ev, d_ev);
  let box = getTarget(d_ev);
  if (box) {
    box.style.left = x + "px";
    box.style.top = y + "px";
  }
}

// 获取元素位置
function getPostion(m_ev, d_ev) {
  const { clientX, clientY } = m_ev;
  const { offsetX, offsetY } = d_ev;
  let x = clientX - offsetX;
  let y = clientY - offsetY;
  return { x, y };
}

// 获取目标元素
function getTarget(e) {
  let target = e.target;
  if (target.className.includes(MOVE_DOM_CLASS)) return target;
  return "";
}

// 是否在可视区域
function inVisibleArea(x, y) {
  console.log("X轴", w_left, x, w_right, w_left < x && x < w_right);
  console.log("Y轴", w_top, y, w_bottom, w_top < y && y < w_bottom);
  return w_left < x && x < w_right && w_top < y && y < w_bottom;
}

**

相关推荐
安冬的码畜日常40 分钟前
【D3.js in Action 3 精译_029】3.5 给 D3 条形图加注图表标签(上)
开发语言·前端·javascript·信息可视化·数据可视化·d3.js
太阳花ˉ1 小时前
html+css+js实现step进度条效果
javascript·css·html
小白学习日记1 小时前
【复习】HTML常用标签<table>
前端·html
john_hjy2 小时前
11. 异步编程
运维·服务器·javascript
风清扬_jd2 小时前
Chromium 中JavaScript Fetch API接口c++代码实现(二)
javascript·c++·chrome
丁总学Java2 小时前
微信小程序-npm支持-如何使用npm包
前端·微信小程序·npm·node.js
yanlele2 小时前
前瞻 - 盘点 ES2025 已经定稿的语法规范
前端·javascript·代码规范
It'sMyGo2 小时前
Javascript数组研究09_Array.prototype[Symbol.unscopables]
开发语言·javascript·原型模式
懒羊羊大王呀2 小时前
CSS——属性值计算
前端·css