var a; document.onmouseup = function() { if (!a) return; a = ""; }; document.onmousemove = function(d) { if (!a) return; d=d||event; a.style.left = (d.clientX - b) + "px"; a.style.top = (d.clientY - c) + "px"; }; function $(o, e) { a = o; b = e.clientX - parseInt(a.style.left); c = e.clientY - parseInt(a.style.top); } script>
1 2 3 4 5 6
效果:
[Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]
实例代码二见:
代码如下:
无标题文档
var obj=document.getElementById("test"); var b; obj.onmousedown=function(e){ b=true; var divLeft=parseFloat(window.getComputedStyle?window.getComputedStyle(obj,null).left:obj.currentStyle.left); var divTop=parseFloat(window.getComputedStyle?window.getComputedStyle(obj,null).top:obj.currentStyle.top); var e=e||event; var divX=e.clientX-divLeft; //计算鼠标和div边框的距离 var divY=e.clientY-divTop; document.onmousemove=function(e){ if(b){ var e=e||event; //兼容IE8及以下 obj.style.left=e.clientX-divX+"px"; obj.style.top=e.clientY-divY+"px"; } } } document.onmouseup=function(){ b=false; } script>