在contenteditable
div中删除"Hello"或"World"的任何字符时,应删除整个单词。
下面的代码适用于笔记本电脑上的ChromeVersion 102.0.5005.115 (Official Build) (64-bit)
,但不适用于Android
手机上的ChromeVersion 102.0.5005.5005.125
。
编辑:我发现该代码在手机Chrome浏览器上不起作用,因为在手机浏览器上,e.key
是Unidentified
。在手机浏览器上,e.key
无法检测到按下了哪个键。也许手机浏览器不支持e.key
,那么我还可以用什么方法来确定在手机浏览器上按下了哪个键?
$('#div-editor').keyup(function(e) {
var $target = $(document.getSelection().anchorNode).closest(".word");
$(".word").each(function(){
if (["Delete", "Backspace"].includes(e.key)) {
$target.remove();
e.preventDefault();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div contenteditable="true" id = "div-editor" >
<span class="word">Hello</span>
<span class="word">World</span>
</div>
尝试以下代码片段
$('#section .word').attr("contenteditable", true);
$(document).on("keyup","#section .word",function(e) {
if (["Delete", "Backspace"].includes(e.key)) {
$(this).remove();
e.preventDefault();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="section">
<span class="word">Hello</span>
<span class="word">World</span>
</div>
$(document).ready(function(){
$('.word').on('keyup',function(e) {
if(e.key == "Backspace" || e.key == "Delete"){
$(this).remove();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div contenteditable="false" id="section">
<span contenteditable="true" class="word">Hello</span>
<span contenteditable="true" class="word">World</span>
</div>