Html拖放使用jQuery w / out拖动 [英] Html Drag and Drop using jQuery w/out Draggable

查看:130
本文介绍了Html拖放使用jQuery w / out拖动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以使用jQuery发布一个简单的drag'n'drop实例而不使用可拖动的行为?根据我的理解,它不应该比10行更长。



我有以下html:

 < div id =containerstyle =width:500px; height:500px;> 
< div id =draggablestyle =width:10px; height:10px; background-color:blue; />
< / div>

我想做一个蓝色的squre可拖动。



我的实现工作正常,但看起来相当怪异,所以我希望能够从你们那里得到一些类。

解决方案

这就是我要做的:

$($#
$ b

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

//仅当实际发生拖动时绑定mousemove
$(document).on({
//将mousemove事件委托给可拖动元素
'mousemove.drag':$。代理(函数(evt){
$(this).css({left:evt.pageX - offset.x,top:evt.pageY - offset.y});
},this),

//取消绑定mouseup上的命名空间事件
'mouseup.drag':function(evt){
$(document).off('。drag');
}
});

返回false;
});

演示: http://jsfiddle.net/sXahK/6/


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.

解决方案

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/

这篇关于Html拖放使用jQuery w / out拖动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆