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

相关推荐
phltxy20 小时前
从零入门JavaScript:基础语法全解析
开发语言·javascript
Kagol21 小时前
JavaScript 中的 sort 排序问题
前端·javascript
cos1 天前
Fork 主题如何更新?基于 Ink 构建主题更新 CLI 工具
前端·javascript·git
摸鱼的春哥1 天前
AI编排实战:用 n8n + DeepSeek + Groq 打造全自动视频洗稿流水线
前端·javascript·后端
nece0011 天前
vue3杂记
前端·vue
Coder_Boy_1 天前
基于SpringAI的在线考试系统设计总案-知识点管理模块详细设计
android·java·javascript
冴羽1 天前
2026 年 Web 前端开发的 8 个趋势!
前端·javascript·vue.js
五仁火烧1 天前
Vue3 项目的默认端口行为
服务器·vue.js·nginx·容器·vue
fengbizhe1 天前
bootstrapTable转DataTables,并给有着tfoot的DataTables加滚动条
javascript·bootstrap
刘一说1 天前
TypeScript 与 JavaScript:现代前端开发的双子星
javascript·ubuntu·typescript