元素跟随鼠标移动

**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;
}

**

相关推荐
神经毒素3 分钟前
WEB安全--XSS--DOM破坏
前端·web安全·xss
不简说26 分钟前
sv-print可视化打印组件不完全指南③
前端·javascript·vue.js
前端摸鱼杭小哥28 分钟前
Vue 开发者狂喜!我在 React 中完美复刻了 v-if/v-for 指令
前端·vue.js·react.js
kovli31 分钟前
红宝书第四讲:JavaScript原始值与引用值行为差异详解
前端·javascript
竹苓32 分钟前
CSS Grid布局:从入门到放弃再到真香
前端
1_2_3_33 分钟前
深入理解 Git 子模块:优化项目管理的利器
前端·github
前端开发同学36 分钟前
前端必看!JSON.parse(JSON.stringify())竟不是万能解?深拷贝的黑暗森林法则
javascript
前端开发同学38 分钟前
程序员必看!被盒模型逼疯的我,看完迎刃而解😎
前端·html
阳树阳树39 分钟前
Svelet 原理初探
前端·javascript
wordbaby43 分钟前
深入理解 CSS 字体加载与解析机制
前端