本来在项目中不是必须的,但是我觉得如果能实现拖动给客户感觉会更好一点,所以就开始写一个拖动,其实网上有很多可以拿过来就用的源码,但是总想自己写一个,因为我觉得大部分代码写的太多了。所以就参考他们的,写我自己的。
实际上就是用了三个事件函数
1.onmousedown 2.onmousemove 3.onmouseup
利用这三个事件函数就可以了,代码如下:
<script type="text/javascript">
var x,y;
function mousedown(obj)
{
obj.onmousemove = mousemove;
obj.onmouseup = mouseup;
oEvent = window.event ? window.event : event;
x = oEvent.clientX;
y = oEvent.clientY;
}
function mousemove()
{
oEvent = window.event ? window.event : event;
var _top = oEvent.clientY - y + parseInt(this.style.top) + "px";
var _left = oEvent.clientX - x + parseInt(this.style.left) +"px";
this.style.top = _top;
this.style.left = _left;
x = oEvent.clientX;
y = oEvent.clientY
}
function mouseup()
{
this.onmousemove = null;
this.onmouseup = null;
}
</script>
var x,y;
function mousedown(obj)
{
obj.onmousemove = mousemove;
obj.onmouseup = mouseup;
oEvent = window.event ? window.event : event;
x = oEvent.clientX;
y = oEvent.clientY;
}
function mousemove()
{
oEvent = window.event ? window.event : event;
var _top = oEvent.clientY - y + parseInt(this.style.top) + "px";
var _left = oEvent.clientX - x + parseInt(this.style.left) +"px";
this.style.top = _top;
this.style.left = _left;
x = oEvent.clientX;
y = oEvent.clientY
}
function mouseup()
{
this.onmousemove = null;
this.onmouseup = null;
}
</script>
html部分是
<div id="div1" style=" 100px; height: 100px; top:10px; left:15px; cursor:move; background-color:Blue; position:absolute;" onmousedown="mousedown(this)" > </div>
注意事项:
1.要拖动的div一定要把position属性设置absolute;否则按流布局的话无法实现拖动。
2.一定要设置top和left的初始值,否则当onmousemove事件触发时就会报错!
存在问题:
1.只能在IE里用,没有实现跨浏览器。
2.在拖动过程中如果鼠标快速移动,就会移出到被拖动层的外面,这时如果松开鼠标,没有清空onmousemove事件,所以当鼠标指向时就会跟着鼠标移动。
文章来源:http://www.cnblogs.com/interboy/archive/2007/05/02/734642.html