如何解决按返回键结束 contenteditable 中的编辑
我创建了一个 html 表并将 td
元素设置为 contenteditable = true
。如果我点击页面上的其他地方,我会“结束”对内容的编辑,这意味着单元格不再突出显示,并且输入字符不会将它们添加到单元格中。
我想通过按回车键来实现这一点。我已经有一个键监听器来防止用户在按下返回键时插入换行符:
document.addEventListener('keydown',function (event) {
if (event.key === 'Enter') {
event.preventDefault();
var value = event.target.innerHTML;
// do something with the value
}
});
如何在按下返回键时“结束”编辑(类似于跳出单元格)?
td
元素都如下所示:
<td class="memory-cell" id="memory-cell-45" data-cell-number="45" width="100" contenteditable="true">0</td>
更新:我最终设置了点击时的 contenteditable = true
并删除了按下返回键时的 contenteditable
属性。
解决方法
将 onkeydown
绑定到文档或最好是可编辑元素,然后删除 keydown 上的 contenteditable
属性(如果按下的是 Enter
键)。
如果你想在 div 之外禁用它,你也可以绑定到 document.querySelector(".memory-cell").onkeydown
。
document.onkeydown = function(event) {
if (event.key === 'Enter') {
event.preventDefault();
document.querySelector(".memory-cell").removeAttribute('contenteditable');
}
}
function enableEditing(element){
//Adds the content editable property to passed element
element.setAttribute('contenteditable',true)
//Focuses the element
element.focus()
}
<table border="1">
<tr>
<td class="memory-cell" onclick="enableEditing(this)" id="memory-cell-45" data-cell-number="45" width="100" contenteditable>0</td>
</tr>
</table>
PS:添加了以下代码段中的附加表格元素,仅供参考
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。