2012-12-18 62 views
0

我有一系列固定高度和宽度的按钮,这些按钮需要在父div内的任何位置可拖动和放置。更改js中的按钮顺序

根据客户端请求,我不能使用任何外部库,meh ...我可以在几秒钟内用jQuery做到这一点,但是,我想这是它的一个缺点:你不能学习更多的基本东西...

我该怎么去做呢?一个问题是,这些按钮是在一个div也是可拖动的,所以我需要小心定位,我只能使用相对。

任何想法如何我可以去做呢?提前致谢。

+0

潜入jQuery UI库? :) – Ian

+0

我不认为这个人得到了很多反馈 – Amberlamps

+0

客户端禁止外部库的原因是什么?像jQuery这样的东西现在已经成为web开发的标准。 – Bojangles

回答

0

Peter-Paul Koch写了一个excellent how-to on drag and drop。我只记得通过写我自己的方式3/4,所以我wrapped that up in a fiddle

function makeDraggable(draggable, container){ 
    // In case you don't want to have a container 
    var container = container || window; 
    // So we know what to do on mouseup: 
    // At this point we're not sure the user wants to drag 
    var dragging = false; 

     // The movement listener and position modifier 
     function dragHandler(moveEvent){ 
      moveEvent.preventDefault(); 

      dragging  = true; 

      // Ascertain where the mouse is 
      var coordinates = [ 
        moveEvent.clientX, 
        moveEvent.clientY 
      ]; 

      // Style properties we need to apply to the element 
      var styleValues = { 
        position : 'absolute', 
        left  : coordinates[0] + 'px', 
        top  : coordinates[1] + 'px' 
      }; 

      // Apply said styles 
      for(property in styleValues){ 
        if(styleValues.hasOwnProperty(property)){ 
          draggable.style[property] = styleValues[property]; 
        } 
      } 
    } 

    function dropHandler(upEvent){ 
     // Only interfere if we've had a drag event 
     if(dragging === true){ 
      // We don't want the button click event to fire! 
      upEvent.preventDefault(); 

      // We don't want to listen for drag and drop until this is clicked again 
      container.removeEventListener('mousemove', dragHandler, false); 
      draggable.removeEventListener('mouseup', dropHandler, false); 

      dragging = false; 
     } 
    } 

    // Where all the fun happens 
    draggable.addEventListener('mousedown', function dragListener(downEvent){ 
     downEvent.preventDefault(); 

     // The drag event 
     container.addEventListener('mousemove', dragHandler, false); 

     // The end of drag, if dragging occurred 
     draggable.addEventListener('mouseup', dropHandler, false); 
    }, false); 
}​ 
+0

请注意,如果速度非常缓慢,可以将示例中的按钮拖出框。在应用推断容器尺寸和位置的位置样式并检查坐标是否在该空间内之前,您可能需要添加一个额外的函数。 – Barney