<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>javascript实现拖动层</title> <style type="text/css"> #test{width:200px; height:200px; background=\‘#\‘" cursor:move; position:absolute; left:100px; top:100px} </style> </head> <body> <div id="test"></div> <script type="text/javascript"> var obj=document.getElementById("test"); var b; obj. 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. if(b){ var e=e||event; //兼容IE8及以下 obj.style.left=e.clientX-divX+"px"; obj.style.top=e.clientY-divY+"px"; } } } document. b=false; } </script> </body> </html>
本文出自 “前端开发” 博客,请务必保留此出处http://maobin.blog.51cto.com/6335599/1359085