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

相关推荐
然我22 分钟前
不用 Redux 也能全局状态管理?看我用 useReducer+Context 搞个 Todo 应用
前端·javascript·react.js
前端小巷子27 分钟前
Web 实时通信:从短轮询到 WebSocket
前端·javascript·面试
DanB241 小时前
html复习
javascript·microsoft·html
呼啦啦呼啦啦啦啦啦啦7 小时前
利用pdfjs实现的pdf预览简单demo(包含翻页功能)
android·javascript·pdf
前端 贾公子10 小时前
vue-cli 模式下安装 uni-ui
前端·javascript·windows
拾光拾趣录10 小时前
链表合并:双指针与递归
前端·javascript·算法
软件20510 小时前
【vue3主题切换】
vue
拼图20910 小时前
element-plus——图标推荐
javascript·vue.js·elementui
期待のcode10 小时前
图片上传实现
java·前端·javascript·数据库·servlet·交互
koooo~11 小时前
JavaScript中的Window对象
开发语言·javascript·ecmascript