Javascript划分定位

时间:2014-01-03 19:20:42

标签: javascript

这是我的简单代码。它包含分区,它在屏幕上的任何位置用鼠标(在x轴上)拖动。在第一次拖动时一切都很完美,但在第二次分割时回到原来的位置,这是屏幕的中心我知道为什么会发生这种情况,但无法弄清楚如何解决这个问题。我的观点是继续将分裂从前一个拖动移动它的坐标移开。

<!DOCTYPE html>
 <html>
   <head>
   </head>

<body style="overflow:hidden">
  <style>
   #screen
   {
    width:200px;
    height:300px;
    position:absolute;
    top:0;bottom:0;left:0;right:0;
    margin:auto;
    border-style:solid;
   }
  </style>

  <script>

   var exit=0;

   document.onmousedown=function(e)
   {
    exit=1;
    x=e.pageX;
    document.onmousemove= function(e)
    {
     if(exit==1)
     {
      y=e.pageX;
      final=x-y;
      document.getElementById("screen").innerHTML=final;
      document.getElementById("screen").style.left=final+"px";
     }
    };
   };

   document.onmouseup=function(e)
   {
    exit=0;
   }

  </script>

  <div id="screen">

</body>
</html>

1 个答案:

答案 0 :(得分:1)

您希望存储“final”值,以便在下次单击时将其用作偏移量。发生的事情是你正在使用鼠标按下鼠标移动X区别来移动对象,但是在第二次点击时你没有考虑到该对象被之前的“最终”值所取代,并且它必须随着该偏移而移动心里! 这是代码片段的工作,以及下面的jsfiddle链接:

   var exit=0;
   var final = 0;

   document.onmousedown=function(e)
   {
       exit=1;
       x=e.pageX + final;
       document.onmousemove= function(e)
       {
         if(exit==1)
         {
              y=e.pageX;
              final=x-y;
              document.getElementById("screen").innerHTML=final;
              document.getElementById("screen").style.left=final+"px";
         }
       };
   };

   document.onmouseup=function(e)
   {
       exit=0;
   }

的jsfiddle:

http://jsfiddle.net/dcasadevall/NELWW/