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

相关推荐
codingWhat1 小时前
介绍一个手势识别库——AlloyFinger
前端·javascript·vue.js
Lee川1 小时前
深度拆解:基于面向对象思维的“就地编辑”组件全模块解析
javascript·架构
进击的尘埃1 小时前
Web Worker 与 OffscreenCanvas:把主线程从重活里解放出来
javascript
codingWhat1 小时前
手撸一个「能打」的 React Table 组件
前端·javascript·react.js
进击的尘埃1 小时前
用 TypeScript 的 infer 搓一个类型安全的深层路径访问工具
javascript
yuki_uix1 小时前
Object.entries:优雅处理 Object 的瑞士军刀
前端·javascript
Lee川1 小时前
JavaScript 面向对象编程全景指南:从原始字面量到原型链的终极进化
javascript·面试
Neptune16 小时前
JavaScript回归基本功之---类型判断--typeof篇
前端·javascript·面试
进击的尘埃6 小时前
微前端沙箱隔离:qiankun 和 wujie 到底在争什么
javascript
子兮曰7 小时前
后端字段又改了?我撸了一个 BFF 数据适配器,从此再也不怕接口“屎山”!
前端·javascript·架构