js判断鼠标点击并移动且跟着一个div

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title></title>
      
        <style type="text/css">
            .div {
                 display: none;
                 position: absolute;
                 width: 30px;
                 height: 30px;
                 margin: -15px 0 0 -15px;
                 background: rgba(37, 0, 255, 0.3);
                 -webkit-border-radius: 50%;
                 -moz-border-radius: 50%;
                 border-radius: 50%;
             }
         </style>
     </head>
 
     <body>
         <div id="div" class="div"></div>
         
         
     </body>
 
 </html>
 <script type="text/javascript">
     window.onload = function() {
         var a = 0
         var oDiv = document.getElementById("div");
        //  window.onmousemove = function(ev) {
        //      var ev = ev || window.event;
        //      var ofLeft = document.documentElement.offsetLeft || document.body.offsetLeft;
        //      var ofTop = document.documentElement.offsetTop || document.body.offsetTop;
        //      var oLeft = ev.clientX + ofLeft;
        //      var oTop = ev.clientY + ofTop;
        //      oDiv.style.display = "block";
        //      oDiv.style.left = oLeft + "px";
        //      oDiv.style.top = oTop + "px";
        //  }
        document.onmouseup = function(){
            oDiv.style.display = "none";
            a = 0;
        }    

        document.onmousedown = function(){
            a = 1
        }

         window.onmousemove = function(ev) {
             if(a===1){
                var ev = ev || window.event;
             var ofLeft = document.documentElement.offsetLeft || document.body.offsetLeft;
             var ofTop = document.documentElement.offsetTop || document.body.offsetTop;
             var oLeft = ev.clientX + ofLeft;
             var oTop = ev.clientY + ofTop;
             oDiv.style.display = "block";
             oDiv.style.left = oLeft + "px";
             oDiv.style.top = oTop + "px";
             }
            
         }
        
       
     }
 </script>

 

posted @ 2021-04-22 13:55  封兴旺  阅读(149)  评论(0编辑  收藏  举报

联系方式: 18274305123(微信同号)