您的位置:首页 > Web前端 > JavaScript

利用JavaScript实现简单的拖动层(只使用于IE)

2008-07-08 15:13 821 查看
实际上就是用了三个事件函数
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>


html部分是
<div id="div1" style="width: 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事件,所以当鼠标指向时就会跟着鼠标移动。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: