【问题标题】:How to activate sortable using mousedown event instead of drag event using Jquery UI Sortable?如何使用 mousedown 事件而不是使用 Jquery UI Sortable 的拖动事件来激活可排序?
【发布时间】:2018-07-17 07:51:39
【问题描述】:

我正在使用 Jquery UI Sortable 对表格行进行重新排序。拖放按预期工作,但我需要使用 moousedown 事件而不是拖动事件来激活可排序。这是相同的Plunker

angular.element(el).sortable({
    cursor: 'pointer',
    helper: fixWidthHelper
}).disableSelection();

function fixWidthHelper(e, ui) {
    ui.children().each(function() {
        angular.element(this).width(angular.element(this).width());
    });
    return ui;
}

【问题讨论】:

  • jQuery UI sortable 没有拖动事件。它刚刚开始和停止事件。请看api.jqueryui.com/sortable
  • @AliSoltani,只有开始拖动,我们才能对项目进行排序。但我也希望使用 mousedown 事件进行排序。
  • 另一件事是据我所知没有办法覆盖 jQuery sortable 中的事件。
  • @UmakantaBehera 您或用户如何知道按下向下箭头键时要移动哪个项目?这不是 sortable 可以做到的,但必须调整项目位置,然后更新 sortable。
  • @Twisty 我想要的是,当用户在任何项目上按下鼠标时,应拖动所选项目,而在鼠标上移时,项目应放在某处。基本上,用户不应该将某些项目拖放到某处。

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


【解决方案1】:

正如我在 cmets 中提到的,.sortable() 必须使用鼠标交互,click + drag + drop,才能移动项目。它无法通过键盘交互移动项目。

您可以编写一个函数来模拟此活动。但是您仍然需要一些方法来“关注”您的一个项目,然后将其移动到不同的位置。你永远不会远离click 事件。也许这就够了。

这是带有一些额外功能的默认可排序示例:

https://jsfiddle.net/Twisty/7r55c9wb/

JavaScript

$(function() {
  function clickFocus(e) {
    $(".ui-state-focus").removeClass("ui-state-focus");
    $(this).addClass("ui-state-focus");
    $(e.target).blur();
  }

  function moveFocused($item, dir) {
    var $parent = $item.parent();
    var $items = $parent.children();
    if (dir == "up" && $item.index() == 0) {
      return false;
    }
    if (dir == "down" && $item.index() == $items.length - 1) {
      return false;
    }
    console.log("Moving Item " + $item.index() + " " + dir);
    var cIndex = $item.index();
    var nIndex;
    var float = $item.detach();
    if (dir == "up") {
      nIndex = cIndex - 1;
      $items.eq(nIndex).before(float);
    }
    if (dir == "down") {
      nIndex = cIndex + 1;
      $items.eq(nIndex).after(float);
    }
    $parent.sortable("refresh");
  }

  $("#sortable").sortable();
  $("#sortable li").click(clickFocus)
  $("html").keyup(function(e) {
    if ($(".ui-state-focus").length == 1) {
      console.log(e.which);
      if (e.which == 38) {
        moveFocused($(".ui-state-focus"), "up");
      }
      if (e.which == 40) {
        moveFocused($(".ui-state-focus"), "down");
      }
    }
  });
  $("#sortable").disableSelection();
});

这允许两者并注意在项目位置更改后,我 refresh 可排序,因此它可以知道所有项目的新位置。

有一个奇怪的警告,我还没有弄清楚。执行clickFocus() 时,我无法从$(document)$("html")$("body")$("#sortable") 捕获keyup 事件。您必须单击文档的任何其他部分才能捕获事件。

【讨论】:

    猜你喜欢
    • 2011-12-30
    • 2010-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多