<div contenteditable="true">
<p>This is an editable paragraph.</p>
<figure>
<img src="http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image1.jpg">
</figure>
<p>This is an editable paragraph.</p>
</div>
我正在摆弄一个内容可编辑的 div。
里面有一个图像,它位于图形标签内。
突出显示图像并按键盘上的删除键后,图像将被删除,但图形标签仍保留在后面。
当我突出显示图像时,如何删除图像旁边的图形标签?
我需要一些 JS 技巧还是我错过了一些明显的东西?
最佳答案
尝试使用 keydown
事件、setTimeout
、.is()
、.remove()
$("div[contenteditable]").on("keydown", function (e) {
if (e.keyCode === 8) {
setTimeout(function () {
if (!$("figure img", e.target).is("*")) {
$("figure", e.target).remove()
}
})
}
})
setTimeout
为在退格键按下事件后从 DOM 中删除 img 提供最小延迟。 !$("figure img", e.target).is("*")
返回 bool 值,指示figure元素是否包含img元素; context 在选择器处设置为 div[contenteditable]
。如果figure元素不包含img元素,则删除figure元素。
关于javascript - 从内容可编辑 div 中删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34005557/