【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拖拽不流畅、鼠标滑动太快导致拖拽物脱离鼠标问题

相关推荐
super_lzb17 小时前
VUE 请求代理地址localhost报错[HPM] Error occurred while trying to proxy request
java·spring·vue·springboot·vue报错
东东51617 小时前
校园短期闲置资源置换平台 ssm+vue
java·前端·javascript·vue.js·毕业设计·毕设
悟能不能悟17 小时前
VUE的国际化,怎么实现
前端·javascript·vue.js
2601_9494800617 小时前
Flutter for OpenHarmony音乐播放器App实战11:创建歌单实现
开发语言·javascript·flutter
Mr Xu_18 小时前
解决 Vue + Axios 热更新导致响应拦截器重复注册的问题
前端·javascript·vue.js
Coder_preston18 小时前
JavaScript学习指南
开发语言·javascript·ecmascript
Jinuss18 小时前
源码分析之React中Scheduler调度器的最小二叉堆
javascript·算法·react.js
a11177618 小时前
电流卡片特效(html网页 开源)
javascript·css·css3
狗都不学爬虫_18 小时前
JS逆向 -最新版 盼之(decode__1174、ssxmod_itna、ssxmod_itna2)纯算
javascript·爬虫·python·网络爬虫·wasm
天天进步201518 小时前
透明的可观测性:剖析 Motia Workbench 与插件系统架构
javascript