Html Drag and Drop using jQuery w/out Draggable

旧街凉风 提交于 2019-12-25 07:57:44

问题


Could anyone post a minimalistic example of drag'n'drop imeplementation using jQuery without using draggable behavior? On my understanding it shouldn't be much longer than 10 lines.

I've the following html:

<div id="container" style="width:500px; height:500px;">
  <div id="draggable" style="width:10px; height:10px; background-color:blue;" />
</div>

I want to make a blue squre draggable so.

I've got my implementation working, but it looks rather monstrous, so I 'd like to get a touch of class from you guys.


回答1:


This is how I would do it:

$('#draggable').on('mousedown', function (evt) {
  var offset = {x: evt.offsetX || evt.originalEvent.layerX, y: evt.offsetY || evt.originalEvent.layerY};

  // bind mousemove only if dragging is actually happening
  $(document).on({
    // delegate the mousemove event to the draggable element
    'mousemove.drag': $.proxy(function(evt) {
      $(this).css({left: evt.pageX - offset.x, top: evt.pageY - offset.y});
    }, this),

    // unbind namespaced events on mouseup
    'mouseup.drag': function (evt) {
      $(document).off('.drag');
    }
  });

  return false;
});

demo: http://jsfiddle.net/sXahK/6/




回答2:


I'm assuming that by "without Draggable" you mean without jQuery UI. You could do something like this:

var dragging = false;
$("#draggable").mousedown(function() {
   dragging = true; 
}).mouseup(function() {
   dragging = false; 
});
$(document).mousemove(function(e) {
    if(dragging) {
        $("#draggable").css({left: e.pageX, top: e.pageY});  
    } 
});

It's far from perfect but it should be enough to get you started. It won't constrain the dragging to the container for example.

Here's a working example.



来源:https://stackoverflow.com/questions/8805403/html-drag-and-drop-using-jquery-w-out-draggable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!