2010-08-10 85 views
0

當我抓住我的可拖動對象時,它們似乎錯誤地對準了右側的網格 - 這讓我感到困惑!jQuery UI Draggable沒有從正確的位置拖動

任何想法如何我可以拖動一個元素,讓它更貼近我的光標?

代碼:

<html> 
    <head> 
     <title></title> 
     <script type="text/javascript" language="javascript" src="sys/jquery-1.4.2.js"></script> 
     <script type="text/javascript" language="javascript" src="sys/jquery-ui-1.8.4.min.js"></script> 
     <style type="text/css"> 
      * { font-family: arial; font-size: 11px; margin: 0; padding: 0; } 
      div#create-container { width: 900px; height: 500px; min-height: 500px; background-color: #666; margin: 0 auto; } 
      div#create-sections { width: 100px; height: 500px; min-height: 500px; background-color: #555; float: left; } 
      ul#node-grid { width: 200px; height: 200px; min-height: 200px; background-color: #777; float: right; } 
      li.grid-node { width: 20px; height: 20px; min-height: 20px; background-color: darkred; display: block; float: left; list-style-type: none; } 
      div.onepx { width: 20px; height: 20px; min-height: 20px; background-color: #000; position: absolute; float: left; margin-left: 40px; margin-top: 40px; } 
     </style> 
     <script type="text/javascript"> 
      $(document).ready(function() { 
      //add sections to page 
       function addSections() { 
        var numParts = 10; 

        var addItems = numParts; 
        var addMoreItems = numParts*10; 
        while (addItems >= 0) { 
         $('div#create-sections').append('<div class="onepx"></div>'); 
         addItems--; 
        } 
        while (addMoreItems > 0) { 
         $('ul#node-grid').append('<li class="grid-node"></li>'); 
         addMoreItems--; 
        } 
       } 

       // init 
       addSections(); 
       $(".onepx").draggable({ snap: '.grid-node', snapMode: 'inner', snapTolerance: 20, containment: '#create-container', opacity: 0.5 }); 
      }); 
     </script> 
    </head> 
    <body> 
     <div id="create-container"> 
      <div id="create-sections"></div> 
      <ul id="node-grid"></ul> 
     </div> 
    </body> 
</html> 

回答

2

的問題來自於造型這裏:

div.onepx { margin-left: 40px; margin-top: 40px; }​ 

如果您刪除這些利潤,它會像你想的光標位置,see an updated example here :)

您可以給#create-sections填充以獲得類似的初始位置效果,如下所示:

div#create-sections { 
    width: 60px;    /* 100 - 40 */ 
    height: 460px;   /* 500 - 40 */ 
    min-height: 460px;  /* 500 - 40 */ 
    background-color: #555; 
    float: left; 
    padding: 40px 0 0 40px; /* top, left: 40px */ 
} 

You can give that version a try here

+0

尼斯,甚至沒有把2和2放在一起然後:) - 我會在9分鐘內接受... – 2010-08-10 09:41:55

+1

@Neurofluxation - 我增加了一點,如果初始位置很重要,給第二個例子一個看:) – 2010-08-10 09:44:49