Javascript 包装用户';在contenteditable div中使用span标记输入(键入或粘贴)

Javascript 包装用户';在contenteditable div中使用span标记输入(键入或粘贴),javascript,jquery,html,Javascript,Jquery,Html,当用户在contenteditable div中键入或粘贴时,如何将用户键入的内容(键入或粘贴)包装在span标记中 我试过: <div id="inputbox" style="border:1px solid lightgrey" contenteditable="true"> <script> $(document).on('input', '#inputbox', function(e) { e.wrap('<span/>'); }); &l

当用户在
contenteditable div
中键入或粘贴时,如何将用户键入的内容(键入或粘贴)包装在
span
标记中

我试过:

<div id="inputbox" style="border:1px solid lightgrey" contenteditable="true">

<script>
$(document).on('input', '#inputbox', function(e) {
    e.wrap('<span/>');
});
</script>

$(文档).on('input','#inputbox',函数(e){
e、 包裹(“”);
});
检查此示例


包装演示
div{
边框:2件纯蓝;
}
p{
背景:黄色;
保证金:4倍;
}
你好

残忍的

世界

$(“p”)。换行符(“”);
您可以执行以下操作:

//you can change 'focusout' to 'input' to wrap the 'span' to each character the user types
$(document).on('focusout', '#inputbox', function(e) {

    $( this).contents().filter(function() {//contents will get all child elements including text nodes
      return this.nodeType === 3;//return only the text nodes in the matched element
    }).wrap('<span/>');

});
//您可以将“focusout”更改为“input”,将“span”包装到用户键入的每个字符
$(文档).on('focusout','#inputbox',函数(e){
$(this).contents().filter(function(){//contents)将获取包括文本节点在内的所有子元素
返回this.nodeType==3;//仅返回匹配元素中的文本节点
}).wrap(“”);
});

同样,只需使用focus$(“input”).focus(函数(){your code wrap here});谢谢,但这不会包装粘贴文本,你能帮我吗?@zoyb当DIV失去焦点时,它会包装粘贴的文本。你在寻找什么样的行为?