vue悬浮组件拖动时出现“黑色禁用图标”并且鼠标在松开的情况下整个组件依然跟着鼠标动的根本原因
·
为什么会出现“黑色禁用图标”?
1,未阻止 mousedown 默认行为
2,浏览器误认为在拖拽背景图
3,user-select: none 不够
4,mousemove 未阻止默认行为
修改 1:在 onMouseDown 中阻止默认行为
onMouseDown(e) {
e.preventDefault(); // ✅ 阻止默认行为
e.stopPropagation(); // ✅ 防止冒泡
this.isDragging = false;
this.startPosition.x = e.clientX;
this.startPosition.y = e.clientY;
this.offset.x = e.clientX - this.position.x;
this.offset.y = e.clientY - this.position.y;
window.addEventListener('mousemove', this.onMouseMove);
window.addEventListener('mouseup', this.onMouseUp);
}
修改 2:在 onMouseMove 中也阻止默认行为(可选但推荐)
onMouseMove(e) {
const moveX = Math.abs(e.clientX - this.startPosition.x);
const moveY = Math.abs(e.clientY - this.startPosition.y);
if (!this.isDragging && (moveX > this.dragThreshold || moveY > this.dragThreshold)) {
this.isDragging = true;
}
if (!this.isDragging) return;
e.preventDefault(); // ✅ 阻止默认行为
e.stopPropagation(); // ✅ 防止冒泡
this.position.x = e.clientX - this.offset.x;
this.position.y = e.clientY - this.offset.y;
// 限制边界
if (this.position.x < 0) this.position.x = 0;
if (this.position.x > window.innerWidth - 66) this.position.x = window.innerWidth - 66;
if (this.position.y < 0) this.position.y = 0;
if (this.position.y > window.innerHeight - 66) this.position.y = window.innerHeight - 66;
}
修改 3:确保所有可拖拽区域都禁用 user-drag
设置一个.no-select 类,然后加在整个拖拽元素上
.no-select {
-webkit-user-select: none !important;
-moz-user-select: none !important;
-ms-user-select: none !important;
user-select: none !important;
-webkit-user-drag: none !important;
user-drag: none !important;
-webkit-touch-callout: none !important;
}
修改 4:避免背景图被拖拽
如果拖拽组件使用了背景图片,虽然 background-image 不应被拖拽,但某些浏览器(尤其是 Safari 和旧版 Chrome)会把带有 background-image 的 div 当作可拖拽元素。所以还需要给使用了背景图片的元素设置ondragstart="return false"属性
<div class="system-title" ondragstart="return false"></div>
<div class="system-bottom" ondragstart="return false"></div>
<div class="system-top" ondragstart="return false"></div>
或者用 JS 绑定:
mounted() {
// 防止背景图被拖拽
const noDragEls = document.querySelectorAll('.system-title, .system-bottom, .system-top');
noDragEls.forEach(el => {
el.ondragstart = () => false;
});
}
最终效果
修改后,拖动悬浮按钮时:
- ✅ 鼠标不会变成黑色禁止图标
- ✅ 不会误触发文本选择
- ✅ 不会拖出图片
- ✅ 拖动流畅,体验良好
更多推荐



所有评论(0)