原生js拖拽指定div
演示demo 2017-11-22 14:56:45

html:

XML/HTML Code复制内容到剪贴板
  1. <!DOCTYPE html>  
  2. <html>  
  3.     <head>  
  4.         <meta charset="UTF-8">  
  5.         <title>原生js拖拽效果</title>  
  6.     </head>  
  7.     <body>  
  8.         <div id="box"></div>  
  9.           
  10.         <script type="text/javascript">  
  11.             var oBox = document.getElementById('box');  
  12.             oBox.onmousedown = function(e){  
  13.                 var oEvent =e || window.event,  
  14.                     disL = oEvent.clientX - oBox.offsetLeft,  
  15.                     disT = oEvent.clientY - oBox.offsetTop,  
  16.                     maxL = document.documentElement.clientWidth - oBox.offsetWidth,  
  17.                     maxT = document.documentElement.clientHeight - oBox.offsetHeight;  
  18.                       
  19.                 document.onmousemove = function(e){  
  20.                     var oEvent = e || window.event,  
  21.                         disX = oEvent.clientX - disL,  
  22.                         disY = oEvent.clientY - disT;  
  23.                           
  24.                         //console.log(disX);  
  25.                     if(disX <=0){ disX =0}  
  26.                     if(disY <=0){ disY =0}  
  27.                     if(disX >=maxL){ disX =maxL}  
  28.                     if(disY >=maxT){ disY =maxT}  
  29.                     oBox.style.left = disX+'px';  
  30.                     oBox.style.top = disY+'px';  
  31.                 }  
  32.                   
  33.             }  
  34.             document.onmouseup=function(){  
  35.             document.onmousemove=null;  
  36.         }  
  37.         </script>  
  38.           
  39.         <style type="text/css">  
  40.             *{ margin:0; padding:0;}  
  41.             #box{ position:absolute; left:0; top:0; width:100px; height:100px; background:#f60;}  
  42.         </style>  
  43.     </body>  
  44. </html>  

 

本文来自于:http://www.yoyo88.cn/demo/225.html

Powered by yoyo苏ICP备15045725号