jquery-ui sortable:如何在拖动时不添加单元格

jquery-ui sortable: how not to add cells on dragging?

本文关键字:添加 单元格 拖动 sortable jquery-ui      更新时间:2023-09-26

我有一些表格,例如:

<table class="table table-hover table-striped" id="mytable">
    <thead>
    <tr>
        <th>#</th>
        <th>Table heading 1</th>
        <th>Table heading 2</th>
        <th>Table heading 3</th>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td>1</td>
        <td>Table cell</td>
        <td>Table cell</td>
        <td>Table cell</td>
    </tr>
    </tbody>
</table>

然后我想制作可排序表的行标题。

$('#mytable thead tr').sortable({
    axis: "x",
    helper: "clone"
}).disableSelection();

问题:

当我开始拖放时,我有 6 个 th -s 而不是 4 个:

<tr class="ui-sortable">
    <th>#</th>
    <th style="
        display: none;">Table heading 1</th>
    <th class="ui-sortable-placeholder" 
        style="
            visibility: hidden;"></th>
    <th>Table heading 2</th>
    <th>Table heading 3</th>
    <th style="
            display: table-cell; 
            width: 343px; 
            height: 37px; 
            position: absolute; 
            z-index: 1000; 
            left: 184px;" 
        class="ui-sortable-helper">Table heading 1</th>
</tr>

..所有的标记都开始变得非常不稳定和不确定:当我th项目拖到桌子上时,我看到所有行的大小都在跳跃。

很明显,发生这种情况是因为th项计数(不等于trtd项的数量)。

如何修复?

每次开始拖动时,它都会创建两个新的th元素。 一个没有显示,所以它似乎不会影响任何东西。第二个是原始元素的占位符,当您拖动它时。未设置此新元素的宽度,因此它会自动调整为列的最大宽度,这似乎是导致它跳来跳去的原因。

为了解决这个问题,我将占位符元素的宽度更改为我们在 start 函数中拖动的元素的宽度。希望这有帮助

start: function(event, ui){
    $(".ui-sortable-placeholder").css({width: $(ui.item).width()}); 

下面是代码,这是我的小提琴

$(function () {
$('#mytable thead tr').sortable({
    axis: "x",
    helper: "clone",
    start: function(event, ui){
        $(".ui-sortable-placeholder").css({width: $(ui.item).width()});    
    }
}).disableSelection();
});