实现代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> body{ position: relative; margin:0; padding:0; width:100%;; height: 1000px; } #box{ height: 400px; width:400px; position: absolute; left:50%; top:50%; margin-left:-200px; margin-top:-200px; background: #ddd; } #small-box{ height: 50px; width:50px; position: absolute; left:0; top:0; background: red; cursor:move ; } </style> </head> <body> <div id="box"> <div id="small-box"></div> </div> <script> window.onload=function(){ var box=document.querySelector('#small-box'); var body=document.querySelector('body'); var index=0; var x1,y1; box.onmousedown=function(e){ index=1; //鼠标按下才能触发onmousemove方法 var x=e.clientX; //鼠标点击的坐标值,x var y=e.clientY; var left= this.style.left; left=left.substr(0,left.length-2); //去掉px var top=this.style.top; top=top.substr(0,top.length-2); x1=parseInt(x-left); y1=parseInt(y-top); }; box.onmousemove=function(e){ if(index===1){ this.style.left=e.clientX-x1+'px'; this.style.top=e.clientY-y1+'px'; if(this.style.left.substr(0,this.style.left.length-2)<0){ this.style.left=0; }; if(this.style.top.substr(0,this.style.top.length-2)<0){ this.style.top=0; }; if(this.style.top.substr(0,this.style.top.length-2)>350){ this.style.top='350px'; }; if(this.style.left.substr(0,this.style.left.length-2)>350){ this.style.left='350px'; }; } }; box.onmouseup=function(e){ index=0; }; body.onmouseup=function(e){ box.onmouseup(); //类似可以index=0; } } </script> </body> </html>
效果图: