问题描述
当我们拖拽一个网页中的内容时,浏览器会默认去搜索引擎中搜索内容,此时会导致拖拽功能的异常,这个是浏览器提供的默认行为,如果不希望发生这个行为,则可以通过return false来取消默认行为,但是这招对IE8不起作用。
实例
名称
拖拽
功能简介
实现屏蔽掉浏览器对于拖拽网页内容时会去搜索引擎搜索的默认行为
源代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#box1 {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
}
#box2 {
width: 100px;
height: 100px;
background-color: yellow;
position: absolute;
left: 200px;
top: 200px;
}
</style>
<script type="text/javascript">
window.onload = function () {
var box1 = document.getElementById("box1");
var box2 = document.getElementById("box2");
var img1 = document.getElementById("img1");
drag(box1);
drag(box2);
};
//为元素绑定拖拽事件的函数
function drag(obj) {
obj.onmousedown = function (event) {
//此处为解决ie8兼容性问题,捕获当前对象
obj.setCapture && obj.setCapture();
event = event || window.event;
var ol = event.clientX - obj.offsetLeft;
var ot = event.clientY - obj.offsetTop;
document.onmousemove = function (event) {
event = event || window.event;
var left = event.clientX - ol;
var top = event.clientY - ot;
obj.style.left = left + "px";
obj.style.top = top + "px";
};
document.onmouseup = function () {
document.onmousemove = null;
document.onmouseup = null;
//此处为解决ie8兼容性问题,释放当前对象
obj.releaseCapture && obj.releaseCapture();
};
//取消除ie8外浏览器的默认行为
return false;
};
}
</script>
</head>
<body>
我是一段文字
<div id="box1"></div>
<div id="box2"></div>
</body>
</html>
问题分析
return false;能够取消掉大部分浏览器的默认行为,但在ie8及以下浏览器中却无效,故需使用ie8所支持的setCapture方法使要进行拖拽的网页中的内容捕获到所有鼠标按下的事件,从而达到无法拖拽去搜索的目的。但是setCapture方法虽然在Firefox中不报错,但是在chrome中却会报错,故需要做好对setCapture方法是否支持的判断。
解决办法
在鼠标对目标元素按下后就立马对该元素调用setCapture方法(调用前要先判断是否支持),并且在鼠标松开后立即释放。当然该方法只是用来针对ie8的,所以还是要在鼠标按下后取消浏览器默认行为。
捕获
obj.setCapture && obj.setCapture();
释放
obj.releaseCapture && obj.releaseCapture();
取消浏览器(现代浏览器)默认行为
return false;
代码解疑
obj.setCapture && obj.setCapture();
obj.releaseCapture && obj.releaseCapture();
以上两句是如下两段代码的简写
if(obj.setCapture){
obj.setCapture();
}
if(obj.releaseCapture){
obj.releaseCapture();
}