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

相关推荐
mCell2 小时前
GSAP ScrollTrigger 详解
前端·javascript·动效
gnip2 小时前
Node.js 子进程:child_process
前端·javascript
codingandsleeping8 小时前
使用orval自动拉取swagger文档并生成ts接口
前端·javascript
白水清风9 小时前
微前端学习记录(qiankun、wujie、micro-app)
前端·javascript·前端工程化
用户22152044278009 小时前
new、原型和原型链浅析
前端·javascript
阿星做前端9 小时前
coze源码解读: space develop 页面
前端·javascript
叫我小窝吧9 小时前
Promise 的使用
前端·javascript
前端康师傅10 小时前
JavaScript 作用域
前端·javascript
云枫晖10 小时前
JS核心知识-事件循环
前端·javascript
eason_fan11 小时前
Git 大小写敏感性问题:一次组件重命名引发的CI构建失败
前端·javascript