html添加删除元素属性,如何使用属性contentEditable删除div内的HTML元素?

该博客讨论了如何在内容可编辑元素中防止用户误删整个元素。通过设置contenteditable='false',可以阻止元素内容被删除。然后,通过监听键盘事件,特别是退格键(Backspace),在Firefox的一个特定回退bug修复中,判断并处理富文本内容的删除,确保用户能正确删除富文本而不会意外移除整个元素。
摘要由CSDN通过智能技术生成

因为要删除整个元素,这是更好地使contenteditable="false",使浏览器不会让一元素的内容被删除。

然后你就可以按如下方式使用该属性在事件处理测试:在最新的Chrome版本

$('#editable').on('keydown', function (event) {

if (window.getSelection && event.which == 8) { // backspace

// fix backspace bug in FF

// https://bugzilla.mozilla.org/show_bug.cgi?id=685445

var selection = window.getSelection();

if (!selection.isCollapsed || !selection.rangeCount) {

return;

}

var curRange = selection.getRangeAt(selection.rangeCount - 1);

if (curRange.commonAncestorContainer.nodeType == 3 && curRange.startOffset > 0) {

// we are in child selection. The characters of the text node is being deleted

return;

}

var range = document.createRange();

if (selection.anchorNode != this) {

// selection is in character mode. expand it to the whole editable field

range.selectNodeContents(this);

range.setEndBefore(selection.anchorNode);

} else if (selection.anchorOffset > 0) {

range.setEnd(this, selection.anchorOffset);

} else {

// reached the beginning of editable field

return;

}

range.setStart(this, range.endOffset - 1);

var previousNode = range.cloneContents().lastChild;

if (previousNode && previousNode.contentEditable == 'false') {

// this is some rich content, e.g. smile. We should help the user to delete it

range.deleteContents();

event.preventDefault();

}

}

});

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值