如何覆盖jQuery ui sortable的拖动事件?

时间:2013-12-06 17:28:01

标签: javascript jquery jquery-ui jquery-ui-sortable jquery-ui-draggable

在jQuery UI网站上,它说“默认情况下,可排序的项目共享可拖动的属性”。我认为这意味着所有可拖动的事件,sortable也应该继承。但是,情况似乎并非如此。对于可排序的网格,我需要像draggable中的“drag”事件,以便我可以手动更新被拖动元素的x和y值。到目前为止,我已经能够使用mousemove事件和一些标志获取拖动元素的X和Y值,但我无法得到它以便可以设置X和Y值。当我尝试设置值时,它们只是在下次触发事件时重置(它可能发生在mousemove事件之后)。有人知道如何实现这个目标吗?

这是我迄今为止尝试过的小提琴:http://jsfiddle.net/turtlewaxer1100/CUXxn/5/

HTML

<div class="row grid span8">
    <div class="well span2 tile">A</div>
    <div class="well span2 tile">B</div>
    <div class="well span2 tile">C</div>
    <div class="well span4 tile">D</div>
</div>

CSS

.placeholder {
    border: 1px solid green;
    background-color: white;
    -webkit-box-shadow: 0px 0px 10px #888;
    -moz-box-shadow: 0px 0px 10px #888;
    box-shadow: 0px 0px 10px #888;
}
.tile {
    height: 100px;
    width: 100px;
}
.grid {
    margin-top: 1em;
}

JS

var dragging = false;

$(function () {
    $(".grid").sortable({
        start: dragging = function(e, ui) {
          return dragging = true;
        },
        stop: dragging = function(e, ui) {
          return dragging = false;
        },
        tolerance: 'pointer',
        revert: 'invalid',
        placeholder: 'span2 well placeholder tile',
        forceHelperSize: true,

        // Drag doesn't work as an event in sortable.
        drag: function() 
        {
            console.log("Drag fired!");
        }
    });

    // My attempt at a custom drag event. (can get values, but can't set them.)
    $(document).mousemove(function(e){
        if(dragging===true)
        {
            // Grab the sortable element being moved. 
            element = $(".ui-sortable-helper");

            // Show the current X and Y values. (get reset after manually setting them below)
            console.log("before: X: " + element.css("left") + ", Y: " + element.css("top"));   

            // Change the X and Y values to something arbitrary.
            element.css("left",0);
            element.css("top",0);

            // Show the X and Y values after the change. 
            console.log("after: X: " + element.css("left") + ", Y: " + element.css("top")); 
        }
    });
});

1 个答案:

答案 0 :(得分:2)

尝试可排序的sort事件。

 sort: function(event, ui) 
        {
            console.log("Drag fired!");
            ui.helper.css("left",0);
            ui.helper.css("top",0);
        }

这是您更新的jsfiddle