拖动的简单实现

这里记录下拖动的简单实现,把下面代码另存为html,在IE中运行即可。

拖拽其实就涉及的鼠标的三个事件,onmousedown,onmouseup,onmousemove,再结合获取鼠标的位置以及层的left和top即可实现类似的效果。

在编码的时候,有两个需要注意的地方,一个是获取当前样式,currentStyle只在ie下有效,故对于非ie我们可以通过getComputedStyle实现(当然,对于这种需要获取的属性不是很多的情况,您也可以直接用obj.style[key]来获取您当前想要的属性值)

function getStyle(o,key){return o.currentStyle? o.currentStyle[key] : document.defaultView.getComputedStyle(o,null)[key]}//'currentStyle' only for ie5.0+

另一个点就是在获取鼠标位置时要用到event,event这个东西很奇怪,ie下是局部变量,moz内核下是全局变量(说法不准确,只是便于理解),所以在获取鼠标位置时候要对event做个判断

	bar.onmousedown = function(e){ 
		e = e?e:window.event; //'event' ie下局部变量,ff下全局变量
		params.isDrag = true;
		params._X = e.clientX; params._Y = e.clientY;
	};

恩,注意以上两点,结合正确的思路其实就可以了,并不难,下面提供代码:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE> New Document </TITLE>
  <META NAME="Generator" CONTENT="EditPlus">
  <META NAME="Author" CONTENT="">
  <META NAME="Keywords" CONTENT="">
  <META NAME="Description" CONTENT="">
 </HEAD>

 <BODY>
  <script type="text/javascript">// <![CDATA[
	function getStyle(o,key){return o.currentStyle? o.currentStyle[key] : document.defaultView.getComputedStyle(o,null)[key]}//'currentStyle' only for ie5.0+

	var drag = function(bar, target){
	var params = {
		startLeft:0,
		startTop:0,
		_X:0,
		_Y:0,
		isDrag:false
	};
	if(getStyle(target,'left') != 'auto'){params.startLeft = getStyle(target,'left')}
	if(getStyle(target,'top') != 'auto'){params.startTop = getStyle(target,'top')}
	bar.onmousedown = function(e){ 
		e = e?e:window.event; //'event' ie下全局变量,ff下局部变量
		params.isDrag = true;
		params._X = e.clientX; params._Y = e.clientY;
	};
	document.onmouseup = function(){
		params.isDrag = false;
		if(getStyle(target,'left') != 'auto'){params.startLeft = getStyle(target,'left')}
		if(getStyle(target,'top') != 'auto'){params.startTop = getStyle(target,'top')}
	};
	document.onmousemove = function(e){
		var e = e?e:window.event;
		if(params.isDrag){
			var curX = e.clientX, curY = e.clientY, desL = curX-params._X+parseInt(params.startLeft), desT = curY-params._Y+parseInt(params.startTop);
			target.style['left'] = desL>=0?desL + 'px':0;
			target.style['top'] = desT>=0?desT + 'px':0;
		}
	}
};
// ]]></script>
<div id="mybox" class="shadow" style="position: absolute; border: 4px solid #ccc; left: 300px; top: 10px; box-shadow: 3px 3px 4px #666;border:1px red solid; ">
<div id="mybar" style="line-height: 24px; padding-left: 10px; background: #eee; border-bottom: 1px solid #ccc; cursor: move;">拖我试试...</div>
<div style="height: 150px; width: 250px; background: #fefefe;">content...</div>
</div>
<script type="text/javascript">// <![CDATA[
var bar = document.getElementById('mybar'), tar = document.getElementById('mybox');
drag(bar,tar);
// ]]></script>
<p>

 </BODY>
</HTML>


你可能感兴趣的:(拖动的简单实现)