0

下面的代码有问题。我需要在 div 上的任意位置抓取 div 并移动它。当
我将变量 resultx 和 resulty 设置为 100 和 50 时,它可以工作,但这意味着 div 仅被其中心抓取。当我需要抓取其他任何地方并且我尝试计算 resultx 和 resulty 时,它下面的方式不起作用并且 div 仅被其边缘移动或根本没有移动。你能看看我的计算有什么问题吗?我试图找到问题很长时间,但最后我认为它看起来在逻辑上是正确的。谢谢

   <!DOCTYPE html>
<html lang='cs'>
  <head>
    <title></title>
    <meta charset='windows-1250'>
    <meta name='description' content=''>
    <meta name='keywords' content=''>
    <meta name='author' content=''>
    <meta name='robots' content='all'>
    <!-- <meta http-equiv='X-UA-Compatible' content='IE=edge'> -->
    <link href='/favicon.png' rel='shortcut icon' type='image/png'>

  <style type="text/css">
   body{margin:0;}
   #desk {height:100%;width:100%;background-color:lightgreen;position:absolute;}
   #flying  {height:100px;width:200px;background-color:lightblue;position:absolute;top:100px; left:100px;}
   #watchit {height:150px;width:200px;background-color:yellow;position:absolute;top:500px; left:800px;}   
  </style>

  <script type="text/javascript">
  var catched=false; //alert(catched);
  var currtop;
  var currleft;
  var resultx;
  var resulty;

  function trim(str){
   return str.replace("px","");
  }


  function moveit(ev){ 

   oflying=document.getElementById("flying"); 
   currtop=oflying.style.top;
   currleft=oflying.style.left;
   currtop=trim(currtop);
   currleft=trim(currleft);


   if(catched){
    //vzdalenostx=100;
    //vzdalenosty=50;
    resultx = ev.clientX - currleft; 
    resulty = ev.clientY - currtop;

    if(resultx<0){resultx=0;}
    if(resulty<0){resulty=0;}
    if(resultx>200){resultx=200;}
    if(resulty>100){resulty=100;}

       //oflying.style.left = (ev.clientX-100) +"px";
       //oflying.style.top = (ev.clientY-50) +"px";
       oflying.style.left = (ev.clientX-resultx) +"px";
       oflying.style.top = (ev.clientY-resulty) +"px";
   } 
  }

  function showresult(ev){
   document.getElementById('watchit').innerHTML=
   'X:'+ev.clientX+'<br />'+
   'Y:'+ev.clientY+'<br />'+
   'catched:'+catched+
   '<br />Currtop:'+currtop+
   '<br />Currleft:'+currleft+
   '<br />resultx:'+resultx+
   '<br />resulty:'+resulty
   ;
  }

  </script>  

  </head>
  <body onLoad="showresult(event)"> 
  <div id="desk" onmousemove="moveit(event);showresult(event);"
                 onmouseup="catched=false;"
                 onmousedown="catched=false;">  
   </div>

  <div id="flying" onmousedown="catched=true;showresult(event);" 
                   onmouseup="catched=false;showresult(event);"  
                   onmousemove="moveit(event);showresult(event);"> 
  </div>

  <div id="watchit">
  </div> 
  </body>
</html>
4

0 回答 0