javaScript——DOM续(五)
拖拽
🧲 问题描述
在网页中拖拽(drag)某些元素或文本时,如果没有正确阻止默认行为,浏览器可能会将拖动的内容带入搜索引擎或新标签页中,导致拖拽功能异常或页面跳转。
✅ 通用解决方案(现代浏览器)
在 onmousedown 事件中,阻止默认行为即可:
element.onmousedown = function(e) {e.preventDefault(); // 推荐使用现代方式// 或者传统方式:return false;
};
✅ e.preventDefault() 是推荐写法,兼容性更好。
⚠️ 问题出现在 IE8 及以下
在 IE8 及更早版本中:
• return false 有时无法阻止默认行为
• 鼠标事件的 preventDefault() 方法不被支持
• 拖拽时页面可能会直接跳转或选中内容
💡 IE8 的兼容方案:使用 setCapture()
element.onmousedown = function(e) {if (element.setCapture) {element.setCapture(); // IE 专有方法,锁定鼠标焦点}return false; // 仍然加上,增强兼容性
};
setCapture() 是做什么的?
• 让当前元素捕获所有鼠标事件(即使鼠标离开该元素也能接收事件)
• 常用于拖拽中保持元素对事件的控制
• IE 专属:仅 IE 支持 setCapture() 和 releaseCapture()
🚫 在现代浏览器(Chrome, Firefox 等)中无效,但不会报错
🚀 推荐跨浏览器写法(拖拽相关)
element.onmousedown = function(e) {e = e || window.event; // IE 兼容// 阻止默认行为if (e.preventDefault) {e.preventDefault();} else {e.returnValue = false; // IE8 及以下}// IE 专用鼠标捕获if (element.setCapture) {element.setCapture();}// 开始拖拽逻辑...
};
📌 小结
方法 | 说明 | 支持 |
---|---|---|
e.preventDefault() | 阻止默认行为 | 现代浏览器支持 |
return false | 传统方式,IE 有时不可靠 | 所有浏览器,但不总是生效 |
setCapture() | IE 专用方法,锁定鼠标事件接收 | 仅 IE 支持 |
e.returnValue = false | IE 专用阻止默认行为 | 仅 IE8 及以下 |
一个拖拽的效果
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title></title><style type="text/css">body {}.circle_one {width: 200px;height: 200px;border: 1px solid #efefef;background-color: red;position: absolute;}.circle_two {margin-top: 40px;width: 400px;height: 150px;border: 1px solid #efefef;background-color: yellow;/* position: absolute; */}</style></head><body><div class="circle_one" id="area"></div><div class="circle_two"></div></body><script type="text/javascript">let circleOne = document.getElementById('area')circleOne.onmousedown = () => {document.onmousemove = (e) => {console.log(e)e = e || window.event;let left = e.pageX;let top = e.pageY;circleOne.style.left = left + 'px';circleOne.style.top = top + 'px';}}circleOne.onmouseup = (e) => {document.onmousemove = null;} </script>
</html>