原生js拖拽指定div

2021-07-09 10:49:26 浏览数 (1)

代码语言:javascript复制
<!DOCTYPE html>  
<html>  
    <head>  
        <meta charset="UTF-8">  
        <title>原生js拖拽效果</title>  
    </head>  
    <body>  
        <div id="box"></div>  
          
        <script type="text/javascript">  
            var oBox = document.getElementById('box');  
            oBox.onmousedown = function(e){  
                var oEvent =e || window.event,  
                    disL = oEvent.clientX - oBox.offsetLeft,  
                    disT = oEvent.clientY - oBox.offsetTop,  
                    maxL = document.documentElement.clientWidth - oBox.offsetWidth,  
                    maxT = document.documentElement.clientHeight - oBox.offsetHeight;  
                      
                document.onmousemove = function(e){  
                    var oEvent = e || window.event,  
                        disX = oEvent.clientX - disL,  
                        disY = oEvent.clientY - disT;  
                          
                        //console.log(disX);  
                    if(disX <=0){ disX =0}  
                    if(disY <=0){ disY =0}  
                    if(disX >=maxL){ disX =maxL}  
                    if(disY >=maxT){ disY =maxT}  
                    oBox.style.left = disX 'px';  
                    oBox.style.top = disY 'px';  
                }  
                  
            }  
            document.onmouseup=function(){  
            document.onmousemove=null;  
        }  
        </script>  
          
        <style type="text/css">  
            *{ margin:0; padding:0;}  
            #box{ position:absolute; left:0; top:0; width:100px; height:100px; background:#f60;}  
        </style>  
    </body>  
</html>  

0 人点赞