【问题标题】:Cancel dragging of a sortable item取消可排序项目的拖动
【发布时间】:2011-07-05 05:35:31
【问题描述】:

一个绝对常见的可排序案例:

<script>
$(function() {
  $("#sortable").sortable();
});
</script>

<ul id="sortable">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

问题。 需要在某些情况下取消拖动项目,Andrew Whitaker 有一个很好的建议,但该方法仅适用于 jquery-ui-draggable 并且对于 sortables 失败:

$("#sortable").sortable({
  start: function() {
    return false; // will still cause `this.helper is null`
  }
});

非常感谢您的建议。

【问题讨论】:

    标签: jquery jquery-ui jquery-ui-sortable


    【解决方案1】:

    Sortable 具有使用sortable('cancel') 调用的“取消”功能。

    来自文档:“取消当前排序的更改并将其恢复到当前排序开始之前的状态。”见http://api.jqueryui.com/sortable/#method-cancel

    示例用法:

    $("#sortable").sortable({
      stop: function(e, ui) {
        if ("I need to cancel this") {
          $(ui.sender).sortable('cancel');
        }
      }
    });
    

    【讨论】:

    • ui.sender 不能在此处使用,因为sender 是项目从一个可排序对象移动到另一个可排序对象时所来自的可排序对象 (api.jqueryui.com/sortable/#event-stop)。如果您想要单个可排序使用$(this).sortable('cancel')
    【解决方案2】:

    false 返回为 fudgey 建议非常适合使事物动态不可排序,但在可排序配置中还有一个 cancel option 可以让您设置静态不可排序:

    $("#sortable").sortable({
        // this prevents all buttons, form fields, and elemens
        // with the "unsortable" class from being dragged
        cancel: ":input, button, .unsortable"
    });
    

    【讨论】:

    • 请注意,应用了取消 CSS 类的元素下方的任何嵌套可排序对象(例如,在嵌套树视图中)也将被禁用排序,即使它们没有应用该类。跨度>
    【解决方案3】:

    sort 函数回调对排序的作用与对可拖动的拖动 (demo) 的作用相同:

    $("#sortable").sortable({
        sort: function() {
            if ($(this).hasClass("cancel")) {
                $(this).sortable("cancel");
            }
        }
    });
    

    【讨论】:

    • 这会引发错误:“Uncaught TypeError: Cannot read property '0' of null”
    • 我也获取了这个错误错误:“Uncaught TypeError: Cannot read property '0' of null”但你的答案不正确..因为我返回 false 然后我的拖动项禁用和第二个时间不拖山墙
    【解决方案4】:

    试试this example

    $('#list1').sortable({ 连接:'ul' }); $('#list2').sortable({ 连接:'ul', 接收:函数(ev,ui){ 如果(ui.item.hasClass(“数字”)) ui.sender.sortable("取消"); } });

    【讨论】:

    • 超级棒.. 花了半天的时间,最终答案就在这里
    • 很棒的实现,基于我需要的类名。
    猜你喜欢
    • 1970-01-01
    • 2012-09-11
    • 1970-01-01
    • 2012-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多