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

相关推荐
睿智的海鸥23 分钟前
Markdown 语法大全详解
开发语言·前端·javascript·css·html
Highcharts.js34 分钟前
用Highcharts如何动态向一个序列添加点
前端·javascript·react.js·highcharts
玖玖passion1 小时前
React 常用 Hooks 函数及使用方法完全指南(useState / useEffect / useRef / useContext / useCallback / useMemo / useReducer)
前端·javascript
TechMasterPlus1 小时前
Hermes 深度解析:React Native 高性能 JavaScript 引擎实践指南
javascript·react native·react.js
VagueVibes1 小时前
Openclaw 快速接入 DeepSeek V4 Pro 指南
javascript
A_nanda2 小时前
VS2022安装QT6.5.3后,如何更新项目配置
前端·javascript·vue.js
heyCHEEMS2 小时前
记录一下自动化构建中 SSE 与子进程管理的三个坑
javascript·node.js
SonoTommy2 小时前
在 Node.js 文件上传中集成 ClamAV 扫描
javascript
Legendary_0083 小时前
Type-C 赋能传统显示器:一线通联,LDR6020 重构显示互联体验
c语言·计算机外设·pd芯片
Live&&learn4 小时前
Vue项目打包后内联字符串不显示的原因
前端·javascript·vue.js