使用JavaScript(而不是HTML5)拖放?

时间:2013-12-11 12:18:37

标签: javascript drag-and-drop

我正在使用HTML5创建一个离线混合Android应用程序。

无论如何,Android上还不支持HTML5的拖放功能,所以我想使用其他方法。

使用JavaScript实现拖放的其他方法是什么?

2 个答案:

答案 0 :(得分:3)

您可以使用jquery-ui-touch-punchMobile Drag And Drop来实现移动设备的拖放。

分别可以在以下链接中找到它们。

http://touchpunch.furf.com/

http://www.stevefenton.co.uk/cmsfiles/assets/File/mobiledragdrop.html

答案 1 :(得分:2)

使用JavaScript运行拖放而不使用任何形式的额外库或内置HTML5函数的基础知识将附加到浏览器中的各种鼠标/触摸事件;

  • mousedown / touchstart

触发mousedown / touchstart时,您将克隆已单击的元素(或移动现有元素)并将其设置为绝对位置,以便您可以在页面上移动它。拖动开始时,您将设置对被拖动元素的引用,以便您的移动事件可以跟踪当前正在移动的内容。一旦触发了此事件并且您有对元素的引用,您可以将mousemove / touchmove事件附加到文档并开始侦听实际移动。

  • mousemove / touchmove

当触发mousemove / touchmove事件时,您可以使用事件位置在屏幕上移动元素。为了获得最佳性能,您可以将mousemove / touchmove事件附加到整个文档而不是单个元素,否则会遇到鼠标移动速度快于更新元素的问题。

  • mouseup / touchend

最后,当触发mouseup / touchend时,您可以使用最终位置来计算droppoint。您还将释放mousemove / touchmove事件以及对被拖动元素的任何引用。

使用JQuery管理触摸事件的快速示例,可以在http://jsfiddle.net/y9f3B/进行测试;

var target = null;

$('#draggables li').on('touchstart', function(e) {
    var target = $(e.currentTarget).clone();
    target.addClass('dragging');

    // run an intial alignment before adding to the dom
    target.css('left', (e.originalEvent.touches[0].clientX - (target.width() / 2)));
    target.css('top', (e.originalEvent.touches[0].clientY - (target.height() / 2)));

    $('body').append(target);

    $(document).on('touchmove', function(e) {
        if (target != null) {
            // move the target
            target.css('left', (e.originalEvent.touches[0].clientX - (target.width() / 2)));
            target.css('top', (e.originalEvent.touches[0].clientY - (target.height() / 2)));
        }
    });

    $(document).on('touchend', function(e) {
        if (target != null) {            
           var x = (target.offset().left + (target.width() / 2));
           var y = (target.offset().top + (target.height() / 2));

           // calculate if were inside of the dropzone
           var offset = $('#dropzone').offset();

            if (x > offset.left && x < (offset.left + $('#dropzone').width()) && y > offset.top && y < (offset.top + $('#dropzone').height())) {
              var dropped = target.clone();
              dropped.removeClass('dragging');

              $('#dropzone').append(dropped);   
            }

           target.remove(); 

           $(document).off('touchmove');
           target.off('touchup');

           target = null;
        }
    });
});
相关问题