【Vue3】弹窗添加鼠标hover上边缘左、下的的拉伸宽度高度操作

需求

鼠标移动上去可以拖拽容器宽度和高度

代码

省略了一些代码,但应该都看得懂吧~就是两条线添加 mousedown 事件,记得 mousemove 要挂载到 document 上!!!

html 复制代码
<div class="line-w" @mousedown="startResize('width')"></div>
<div class="line-h" @mousedown="startResize('height')"></div>
js 复制代码
const containerWidth = ref(500);
const containerHeight = ref(640);
const isResizing = ref(false);
const resizeDirection = ref('');
const contentRef = ref<HTMLElement>();
function startResize(direction: string) {
  isResizing.value = true;
  resizeDirection.value = direction;

  document.onselectstart = () => false;
  document.ondragstart = () => false;
  document.addEventListener('mousemove', onMouseMove);
  document.addEventListener('mouseup', onMouseup);
}

function onMouseup() {
  console.log('mouseup');
  isResizing.value = false;
  document.onselectstart = null;
  document.ondragstart = null;
  document.removeEventListener('mousemove', onMouseMove);
  document.removeEventListener('mouseup', onMouseup);
}

function onMouseMove(e: MouseEvent) {
  console.log('mousemove');
  if (!isResizing.value) return;
  const { clientX, clientY } = e;
  if (resizeDirection.value === 'width') {
    const w = contentRef.value.getBoundingClientRect().right - clientX;
    containerWidth.value = w < 450 ? 450 : w;
  } else {
    const h = clientY - contentRef.value.getBoundingClientRect().top;
    containerHeight.value = h < 640 ? 640 : h;
  }
}

参考

JS拖拽不流畅、鼠标滑动太快导致拖拽物脱离鼠标问题

相关推荐
linux_cfan2 小时前
16 · `custom-media-element`:属性拦截与转发
前端·javascript·音视频
右耳朵猫AI3 小时前
Web前端周刊2026W38 | React 19.3 发布、StyleX 深潜、jsdom 30.1 提速
前端·javascript·react.js·typescript·node.js
落魄大学生之流水线上谋生计3 小时前
GreenLife Carbon · OpenHarmony 智慧低碳生态平台
javascript
福兮说3 小时前
用 IndexedDB 存用户的文件,我踩过的五个坑
前端·javascript
胡志辉的博客4 小时前
【完全开源】IP 纯净度检测 可一键部署到自己的CF
前端·javascript·chrome·ip·chromium
Hilaku5 小时前
作为面试官,我最怕遇到什么样的候选人?
前端·javascript·程序员
溪语流沙5 小时前
Django + Vue电商项目第001讲:开篇|注册登录加增删改查,那不是电商
redis·python·mysql·docker·typescript·django·vue
程序员阿黄5 小时前
基于 Django 与 Vue 3 的智能实验室预约系统设计与实现
后端·python·mysql·django·vue·毕设
web3d5205 小时前
01-用 Leafletjs 10 分钟搭一张水利一张图(Vue3 + Vite 实战)
前端·javascript
.Hypocritical.5 小时前
Vue CLI(vue-cli)和 Vite 超详细对比
vue