<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
#drag{
position: fixed;
top:100px;
left: 100px;
width: 100px;
height: 100px;
background: #cdc;
}
</style>
</head>
<body>
<div id="drag">
</div>
</body>
<script>
var dragFn,pX,pY,sX,sY,dropFn,dragFlag=false,w=window;
var dom=document.getElementById("drag");
dom.addEventListener("mousedown",dragFn=function (event) {
dragFlag=true;
console.log(dom.style.left+"");
pX = parseInt(w.getComputedStyle(dom,null)['left']); //获得初始位置
pY = parseInt(w.getComputedStyle(dom,1)">null)['top']);
sX=event.clientX-pX;
sY=event.clientY-pY; //
});
addEventListener('mouseup',dropFn = function(){ dragFlag = false; });设置为false,禁止拖动
addEventListener('mousemove',mFn = (event){ onDrag(event); })
onDrag(event) {
if(dragFlag){ 先检验是否可以拖动
var l= (event.clientX -sX);
var t = (event.clientY - sY);
var wl=window.innerWidth-dom.offsetWidth;
var wt=window.innerHeight-dom.offsetHeight; 页面的宽度减去dom的宽度
if (l<0){l=0;}
if (l>wl){l=wl;} 不得超出屏幕的宽度
if (t<0){t=0if (t>wt){t=wt;}
dom.style.left = l+ 'px';
dom.style.top = t+ 'px';
}
}
</script>
</html>