Reorder HTML table rows using drag-and-drop

后端 未结 7 508
無奈伤痛
無奈伤痛 2021-01-29 23:00

I have a jQuery function to move table rows up and down. I do not know how to save the data, nor get the position of each row. I am using PHP to show the table rows.

How

7条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-29 23:52

    Apparently the question poorly describes the OP's problem, but this question is the top search result for dragging to reorder table rows, so that is what I will answer. I wasn't interested in bringing in jQuery UI for something so simple, so here is a jQuery only solution:

    $(".grab").mousedown(function(e) {
      var tr = $(e.target).closest("TR"),
        si = tr.index(),
        sy = e.pageY,
        b = $(document.body),
        drag;
      if (si == 0) return;
      b.addClass("grabCursor").css("userSelect", "none");
      tr.addClass("grabbed");
    
      function move(e) {
        if (!drag && Math.abs(e.pageY - sy) < 10) return;
        drag = true;
        tr.siblings().each(function() {
          var s = $(this),
            i = s.index(),
            y = s.offset().top;
          if (i > 0 && e.pageY >= y && e.pageY < y + s.outerHeight()) {
            if (i < tr.index())
              tr.insertAfter(s);
            else
              tr.insertBefore(s);
            return false;
          }
        });
      }
    
      function up(e) {
        if (drag && si != tr.index()) {
          drag = false;
          alert("moved!");
        }
        $(document).unbind("mousemove", move).unbind("mouseup", up);
        b.removeClass("grabCursor").css("userSelect", "none");
        tr.removeClass("grabbed");
      }
      $(document).mousemove(move).mouseup(up);
    });
    .grab {
      cursor: grab;
    }
    
    .grabbed {
      box-shadow: 0 0 13px #000;
    }
    
    .grabCursor,
    .grabCursor * {
      cursor: grabbing !important;
    }
    
    
    Table Header
    Table Cell 1
    Table Cell 2
    Table Cell 3

    Note si == 0 and i > 0 ignores the first row, which for me contains TH tags. Replace the alert with your "drag finished" logic.

提交回复
热议问题