元素跟随鼠标移动

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

**

相关推荐
冴羽2 分钟前
3 招让你的 Shadcn 出海应用性能提升 40 倍
前端·javascript·next.js
中议视控7 分钟前
网络中控系统通过推流软件实现可视化:RTSP,H265,WEB等推流
前端·网络
Hsuna12 分钟前
Tailwind CSS 比起传统CSS框架无法实现的一些功能
前端·react.js
SilentSamsara13 分钟前
装饰器基础:从闭包到装饰器的自然演变
开发语言·前端·vscode·python·青少年编程·pycharm
咸鱼翻身更入味14 分钟前
Agent流式输送
前端
摇滚侠1 小时前
11 空间转换 前端 Web 开发 HTML5 + CSS3 + 移动 web 视频教程,前端web入门首选黑马程序员
前端·css·html·css3·html5
小李子呢02111 小时前
前端八股网络浏览器---输入 URL 到页面呈现
前端·网络
Hello--_--World2 小时前
Vue:虚拟Dom
前端·javascript·vue.js