元素跟随鼠标移动

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

**

相关推荐
Never_Satisfied5 分钟前
在HTML & CSS中,nth-child、nth-of-type详解
前端·css·html
神奇程序员11 分钟前
不止高刷:明基 RD280UG 在编码场景下的表现如何
计算机外设
睡不着的可乐28 分钟前
createElement → VNode 是怎么创建的
前端·javascript·vue.js
光影少年28 分钟前
前端css如何实现水平垂直居中?
前端·javascript·css
C澒44 分钟前
SLDS 自营物流系统:Pickup 揽收全流程
前端·架构·系统架构·教育电商·交通物流
摸鱼的春哥1 小时前
把白领吓破防的2028预言,究竟讲了什么?
前端·javascript·后端
infiniteWei1 小时前
SKILL.md 触发机制与设计规范:避免“写了不触发”
java·前端·设计规范
慧一居士1 小时前
SVG图片介绍和使用
前端
Rysxt_1 小时前
Uniapp全局配置教程
前端·uniapp
阿珊和她的猫1 小时前
深入理解与使用 Cookie:Web 开发中的关键机制
前端·状态模式