You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在HTML/CSS/jQuery中实现可拖拽表格行并保留contenteditable功能

解决表格行拖拽后contenteditable属性失效的问题

我刚碰到过类似的情况,问题根源就在你调用的.disableSelection()方法上!这个方法会全局禁用元素的文本选择功能,而contenteditable元素要正常工作,必须允许用户选中文本和输入内容,所以拖拽功能启用后,可编辑列就被间接锁死了。

给你两个简单的解决方案:


方案一:移除.disableSelection()(推荐)

jQuery UI的sortable组件在后续版本里已经优化了拖拽时的文本选择问题,完全不需要再手动调用.disableSelection()。直接去掉这个方法就行,既保留拖拽功能,又不影响可编辑列:

修改后的jQuery代码:

var fixHelperModified = function(e, tr) {
  var $originals = tr.children();
  var $helper = tr.clone();
  $helper.children().each(function(index) {
    $(this).width($originals.eq(index).width())
  });
  return $helper;
};

$("#sort tbody").sortable({
  helper: fixHelperModified
});

你的HTML代码可以保持不变:

<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<table id="sort" class="grid" title="Kurt Vonnegut novels">
  <tbody>
    <tr><td class="InputBox_RowClass">1</td><td><p contenteditable='true'>1969</p></td><td>Slaughterhouse-Five</td><td>A+</td></tr>
    <tr><td class="InputBox_RowClass">2</td><td><p contenteditable='true'>1952</p></td><td>Player Piano</td><td>B</td></tr>
    <tr><td class="InputBox_RowClass">3</td><td><p contenteditable='true'>1963</p></td><td>Cat's Cradle</td><td>A+</td></tr>
    <tr><td class="InputBox_RowClass">4</td><td><p contenteditable='true'>1973</p></td><td>Breakfast of Champions</td><td>C</td></tr>
    <tr><td class="InputBox_RowClass">5</td><td><p contenteditable='true'>1965</p></td><td>God Bless You, Mr. Rosewater</td><td>A</td></tr>
  </tbody>
</table>

方案二:单独启用可编辑元素的选择功能

如果你因为某些原因必须保留.disableSelection(),可以在之后针对所有contenteditable元素调用.enableSelection()来恢复它们的文本选择权限:

var fixHelperModified = function(e, tr) {
  var $originals = tr.children();
  var $helper = tr.clone();
  $helper.children().each(function(index) {
    $(this).width($originals.eq(index).width())
  });
  return $helper;
};

$("#sort tbody").sortable({
  helper: fixHelperModified
}).disableSelection();

// 恢复可编辑元素的选择功能
$("[contenteditable='true']").enableSelection();

测试一下,两种方案都能让你的年份列重新变成可编辑状态,同时行拖拽功能也能正常工作。

内容的提问来源于stack exchange,提问作者Jie Hu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 09:08:18