元素跟随鼠标移动

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

**

相关推荐
qq_4069810340 分钟前
c++ lamda(三)Lambda表达式
java·前端·c++
zhanlang021743 分钟前
HTML 零基础入门到企业实战【第五章 5.4】内嵌网页 iframe 标签:嵌入网页、视频、地图实战
前端·html·音视频
FYKJ_20101 小时前
springboot同人周边订单管理系统48955-计算机毕业设计、课程设计
java·javascript·vue.js·spring boot·django·php·课程设计
总要学点什么1 小时前
第106篇:三维特效-流动线效果——让一颗光点沿整条线一路滚到头
开发语言·javascript·ecmascript·gis·webgl·材质·cesium
2分钟速写快排8 小时前
孔乙己的茴字有多少种写法?|AI 对话实时通信的三种实现
前端·javascript·github
Penge66610 小时前
JavaScript:BOM 详解
前端
Penge66611 小时前
Vite vs Webpack:前端构建工具原理与实战
前端
Penge66611 小时前
前端包管理工具:npm、Yarn、pnpm 快速入门
前端
Penge66611 小时前
Sass 了解
前端
Penge66611 小时前
Webpack 打包从 0 到 1 实战笔记
前端