jQuery UI - 拖动函数回调偏移不会在拖动事件上更新

时间:2014-06-05 11:27:00

标签: jquery jquery-ui drag-and-drop offset jquery-ui-draggable

我正在使用jQuery拖放来构建用于设计布局的应用程序,因此它需要100%准确。我遇到的问题是draggables位置似乎是在drag事件之前计算的。因此,一旦元素被删除,记录的位置总是略微超出。

例如:我将可拖动的10px放置在droppable的顶部,10px从左边放下然后放下它。当我检查Chrome检查器中的顶部和左侧位置时,它从顶部显示为10px,从左侧显示为9px。

我已经设置了一个小提琴演示:http://jsfiddle.net/ELS8A/3/

请参阅下面的代码(这取自更大的项目):

HTML:

<div class="boundary"></div>
<div class="drag"></div>

<p class="clone_pos">|</p>

CSS:

body {
    margin:0;
}
.boundary {
    width:300px;
    height:300px;
    background:lightblue
}
.drag {
    width:50px;
    height:50px;
    background:pink;
}

jQuery的:

var in_boundary = false;

jQuery('.drag').draggable({
    helper: 'clone',
    revert: 'invalid',
    drag : function ( event, ui ) { dragging(ui); },
});

jQuery('.boundary').droppable({
    drop: function (ev, ui) { drop_it(this, ui); },
    accept: '.drag',
    tolerance: 'fit',
    over : function( event, ui ) { inside_boundary(ui.helper); },
    out : function( event, ui ) { outside_boundary(ui.helper); },
});

function drop_it(boundary, clone) {
    b_offset = jQuery(boundary).offset(); //get the boundary offset x, y
    b_top = b_offset.top;
    b_left = b_offset.left;

    d_offset_left = (clone.offset.left - b_left); //set positioning for dropped
    d_offset_top = (clone.offset.top - b_top);

    d_clone = jQuery(clone.helper).clone(false) //clone helper
    .removeClass('ui-draggable-dragging') //remove dragging classes
    .removeClass('ui-draggable') //remove dragging classes
    .css({
        position: 'absolute',
        left: d_offset_left,
        top: d_offset_top
    })

    jQuery(boundary).append(d_clone); //append clone to boundary
}

function inside_boundary(this_elem){
    in_boundary = true;
    jQuery(this_elem).css('background', 'blue'); 
}

function outside_boundary(this_elem){
    in_boundary = false;
    jQuery(this_elem).css('background', 'pink');
}        

function dragging(this_ui){ 
    if( in_boundary ){//in_boundary? then start tracking coords 
        boundary = jQuery('.boundary');
        this_draggable = this_ui.helper;//get reference to clone

        b = get_trbl(boundary, 'absolute');//t, r, b, l of boundary
        clone = get_trbl(this_draggable, 'absolute');//t, r, b, l of clone

        clone['top'] -= b['top'];//get clone coords relative to boundary        
        clone['left'] -= b['left'];
        jQuery('.clone_pos').text('TOP: '+clone['top']+', LEFT: '+clone['left']);
    }
}

function get_trbl(elem){//get top, right, bottom, left offset
    tmp = {};
    elem_offset = elem.offset();

    elem_top = elem_offset.top;
    elem_left = elem_offset.left;
    elem_right = elem_left + elem.width();
    elem_bottom = elem_top + elem.height();

    tmp['left'] = elem_left;
    tmp['top'] = elem_top;
    tmp['right'] = elem_right;
    tmp['bottom'] = elem_bottom;
    return tmp;
}

0 个答案:

没有答案