development

테이블과 tr 너비로 정렬 가능한 jquery UI

big-blog 2020. 6. 8. 08:01
반응형

테이블과 tr 너비로 정렬 가능한 jquery UI


테이블 그리드를 정렬 가능하게하기 위해 jQuery UI를 정렬 가능하게 사용하고 있습니다. 코드는 정상적으로 작동하는 것 같지만 tds에 너비를 추가하지 않기 때문에 드래그 tr하면 내용이 축소됩니다.

예를 들어; 드래그를 시작할 때 테이블 행이 500px이면 300px가됩니다. 그리드에 너비가 정의되어 있지 않기 때문에 발생한다고 가정합니다. tds ( fixliquid)에 두 개의 클래스를 사용하고 있기 때문 입니다.

fix클래스하게 td콘텐츠 폭 같고 liquid차종 td폭을 100 %. 너비를 tds 에 할당하지 않고 그리드 테이블에 대한 나의 접근 방식입니다 .

내 접근 방식으로 정렬 가능한 작업을 수행하는 방법을 알고 있습니까?


나는 여기서 답을 찾았다 .

원본에 너비를 추가하는 대신 행을 복제하도록 약간 수정했습니다.

  helper: function(e, tr)
  {
    var $originals = tr.children();
    var $helper = tr.clone();
    $helper.children().each(function(index)
    {
      // Set helper cell sizes to match the original sizes
      $(this).width($originals.eq(index).width());
    });
    return $helper;
  },

도움이 될 것 같습니다.

.ui-sortable-helper {
    display: table;
}

여기에 선택된 답변은 정말 좋은 해결책이지만 원래 JS 바이올린 ( http://jsfiddle.net/bgrins/tzYbU/ )에 명백한 심각한 버그가 있습니다 . 가장 긴 행을 드래그하십시오 ( God Bless You, Mr Rosewater ) 및 나머지 셀 너비가 축소됩니다.

즉, 드래그 한 셀의 셀 너비를 고정하는 것만으로는 충분하지 않습니다. 또한 테이블의 너비를 수정해야합니다.

$(function () {
    $('td, th', '#sortFixed').each(function () {
        var cell = $(this);
        cell.width(cell.width());
    });

    $('#sortFixed tbody').sortable().disableSelection();
});

JS 피들 : http://jsfiddle.net/rp4fV/3/

이렇게하면 첫 번째 열을 드래그 한 후 테이블이 축소되는 문제가 해결되지만 새로운 열이 도입됩니다. 테이블의 내용을 변경하면 셀 크기가 수정됩니다.

내용을 추가하거나 변경할 때이 문제를 해결하려면 너비 설정을 지워야합니다.

$('td, th', '#sortFixed').each(function () {
    var cell = $(this);
    cell.css('width','');
});

그런 다음 컨텐츠를 추가 한 다음 너비를 다시 수정하십시오.

이것은 특히 테이블에서 드롭 자리 표시자가 필요하기 때문에 완벽한 솔루션이 아닙니다. 이를 위해 시작시 자리 표시자를 작성하는 함수를 추가해야합니다.

$('#sortFixed tbody').sortable({
    items: '> tr',
    forcePlaceholderSize: true,
    placeholder:'must-have-class',
    start: function (event, ui) {
        // Build a placeholder cell that spans all the cells in the row
        var cellCount = 0;
        $('td, th', ui.helper).each(function () {
            // For each TD or TH try and get it's colspan attribute, and add that or 1 to the total
            var colspan = 1;
            var colspanAttr = $(this).attr('colspan');
            if (colspanAttr > 1) {
                colspan = colspanAttr;
            }
            cellCount += colspan;
        });

        // Add the placeholder UI - note that this is the item's content, so TD rather than TR
        ui.placeholder.html('<td colspan="' + cellCount + '">&nbsp;</td>');
    }
}).disableSelection();

JS 피들 : http://jsfiddle.net/rp4fV/4/


IE8에서는 행 복제가 잘 작동하지 않지만 원래 솔루션은 작동하지 않는 것 같습니다.

jsFiddle로 테스트했습니다 .


테이블을 정렬 할 준비가되면이 코드를 호출하면 테이블 구조를 손상시키지 않고 td 요소가 고정됩니다.

 $(".tableToSort td").each(function () {
            $(this).css("width", $(this).width());
        });  

Keith의 솔루션은 훌륭하지만 Firefox에서 약간 혼란을 일으켜 colspan을 추가하지 않고 신호를 줄였습니다. (무릎에 오래된 JS 스트링 타입 통증)

이 줄 바꾸기 :

 cellCount += colspan;

와:

 cellCount += colspan-0;

문제를 해결합니다. (js는 변수를 문자열 대신 숫자로 취급해야하므로)


Dave James Miller's answer worked for me, but because of the layout of the container divs on my page, the helper that drags with the mouse cursor is offset from the position of my mouse. To fix that, I added the following to the helper callback

$(document.body).append($helper);

Here is the complete callback with the above line added:

helper: function (e, tr) {
  var $originals = tr.children();
  var $helper = tr.clone();
  $helper.children().each(function (index) {
    // Set helper cell sizes to match the original sizes
    $(this).width($originals.eq(index).width());
  });

  // append it to the body to avoid offset dragging
  $(document.body).append($helper);

  return $helper;
}

I would have added this as a comment to Dave's answer, but I did not have enough rep on this account.


It seems like disableSelection() - method is bad and deprecated nowadays. I can't use text inputs inside sort-able row anymore in Mozilla Firefox 35.0. It just isn't focusable anymore.


$(function() {
    $( "#sort tbody" ).sortable({
        update: function () {
                                var order = $(this).sortable("toArray").join();
                                $.cookie("sortableOrder", order);
                        }
    });
    if($.cookie("sortableOrder")){
        var order = $.cookie("sortableOrder").split(",");
        reorder(order, $("#sort tbody"));
    }
    function reorder(aryOrder, element){
      $.each(aryOrder, function(key, val){
              element.append($("#"+val));
      });
    }
  });

jsFiddle

After a lot of different attempts I just tried a simple solution which completes the solution of Dave James Miller to prevent the table of shrinking while dragging the largest row. I hope it will helps :)

// Make sure the placeholder has the same with as the orignal
var start = function(e, ui) {
    let $originals = ui.helper.children();
    ui.placeholder.children().each(function (index) {
        $(this).width($originals.eq(index).width());
    });
}
// Return a helper with preserved width of cells
var helper = function(e, tr) {
    let $helper = tr.clone();
    let $originals = tr.children();
    $helper.children().each(function (index) {
        $(this).width($originals.eq(index).outerWidth(true));
    });
    return $helper;
};

Apply the sortable to the table's tbody element and just set the helper to 'clone', as described in jquery-ui's API

$("$my-table-tbody").sortable({
    helper: "clone"
});

참고URL : https://stackoverflow.com/questions/1307705/jquery-ui-sortable-with-table-and-tr-width

반응형