JS简易拖拽效果

模仿《javascript权威指南》写了个简易拖拽程序,麻雀虽小五脏俱全。
原理:注册mousemove事件,使元素跟随鼠标挪动;注册mouseup事件,移除mousemove事件,使得松开鼠标时元素不再跟随移动,能够固定在指定位置。在mousedown事件中注册mousemove事件和mouseup事件,这样便可完成一次完整的拖拽。

重点:IE中setCapture()的应用。它的作用是捕捉所有的MouseEvent,设置完成后,即使鼠标移出窗口注册的鼠标事件仍然能够被触发。它在此处的作用是当鼠标移动过快越出元素的边界使得原本将要失效的mousemove事件依然能够发挥作用。在ff和chrome中,由于没有对应的设置,可以把mousemove和mouseup事件指定到docuemnt对象上,这样不管鼠标怎么移动,都在document上;其实在ie上这么写也行,那就不用设置setCapture()了,它和设置了的相比唯一的区别是当元素向右移出窗口边界时,元素始终保持在可视范围内。

<!docType html>
<html>
<head>
<style type="text/css">
#drag {border:1px solid blue;width:100px;height:100px;position:absolute;}
</style>
</head>
<body>
<input id="x"  />
<input id="y"  />
<div id="drag"></div>

<script><!--
var drag = document.getElementById('drag');
var inputX = document.getElementById('x');
var inputY = document.getElementById('y');
if(document.attachEvent){
drag.attachEvent('onmousedown',dragHandle);
}else{
drag.addEventListener('mousedown', dragHandle,false);
}
function dragHandle(event){
	var event = event||window.event;
	var startX = drag.offsetLeft;
	var startY = drag.offsetTop;
	var mouseX = event.clientX;
	var mouseY = event.clientY;
	var deltaX = mouseX - startX;
	var deltaY = mouseY - startY;
	if(document.attachEvent){
		drag.attachEvent('onmousemove',moveHandle);
		drag.attachEvent('onmouseup',upHandle);
		drag.attachEvent('onlosecapture',upHandle);
		drag.setCapture();
	}else{
		document.addEventListener('mousemove',moveHandle,true);
		document.addEventListener('mouseup',upHandle,true);
	}
	function moveHandle(event){
		var event = event||window.event;
		drag.style.left = (event.clientX - deltaX)+"px";
		drag.style.top = (event.clientY - deltaY)+"px";
		inputX.value=drag.style.left;
		inputY.value=drag.style.top;
	}
	function upHandle(){
		if(document.attachEvent){
			drag.detachEvent('onmousemove',moveHandle);
			drag.detachEvent('onmouseup',upHandle);
			drag.detachEvent('onlosecapture',upHandle);
			drag.releaseCapture();
		}else{
			document.removeEventListener('mousemove',moveHandle,true);
			document.removeEventListener('mouseup',upHandle,true);
		}
	}

}
//--</script>
</body>
</html>

当然此例还可以扩展,比如限定拖拽范围不允许移动到可视范围外等,只要修改mousemove方法即可。

你可能感兴趣的:(JavaScript,IE,setcapture)