使用JqueryUI draggable(),如果元素没有拖动一定距离,我怎么能还原?

时间:2013-01-09 03:44:25

标签: jquery-ui jquery-ui-draggable

这样的事情:

$("#0").draggable({
                    handle:'#borderItem #statementType #statementContent',

                    cursor: "move",
                    axis: "x",
                    stop: function(event, ui) {

                        var direction = (ui.originalPosition.left > ui.position.left) ? 'left' : 'right';
                        var distance = 0;
                        if (direction == "left")
                        {
                            distance = ui.originalPosition.left - ui.position.left;
                        }
                        else
                        {
                            distance = ui.position.left - ui.originalPosition.left;
                        }
                        if (distance>75)
                        {
                            self.articleSlid(direction);

                        }
                        else
                        {
                           // Revert!
                        }
                    }
                });

2 个答案:

答案 0 :(得分:0)

我使用以下代码完成了它:

                var startTop = $("#0").outerHeight() + $("#0").position().top;
                var startLeft = $("#0").position().left;
                $("#0").draggable({
                    handle:'#borderItem #statementType #statementContent',

                    cursor: "move",
                    axis: "x",
                    stop: function(event, ui) {

                        var direction = (ui.originalPosition.left > ui.position.left) ? 'left' : 'right';
                        var distance = 0;
                        if (direction == "left")
                        {
                            distance = ui.originalPosition.left - ui.position.left;
                        }
                        else
                        {
                            distance = ui.position.left - ui.originalPosition.left;
                        }
                        if (distance>75)
                        {
                            self.articleSlid(direction);

                        }
                        else
                        {
                            $("#0").animate({left: startLeft},"slow");
                        }
                    }
                });

答案 1 :(得分:0)

您的解决方案正在运行,但该可放置容器也接受了该元素。

您应该使用还原回调来测试您的条件是否符合:

$("#0").draggable(
{
  ...,
  revert: function(event, ui)
  {
     //Test your position
     var position = ...;
     if(position === false)
     {
        //revert the element by returning true
        return true;
     }
     else
     {
        //return false so that the element does not revert
        return false;
     }
  },
  ...
} );