当用户在contenteditable div
中键入或粘贴时,如何在span
标记内包装用户键入的内容(键入或粘贴)。
我试过了:
<div id="inputbox" style="border:1px solid lightgrey" contenteditable="true">
<script>
$(document).on('input', '#inputbox', function(e) {
e.wrap('<span/>');
});
</script>
答案 0 :(得分:0)
检查此示例
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>wrap demo</title>
<style>
div {
border: 2px solid blue;
}
p {
background: yellow;
margin: 4px;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Hello</p>
<p>cruel</p>
<p>World</p>
<script>
$( "p" ).wrap( "<div></div>" );
</script>
</body>
</html>
答案 1 :(得分:0)
您可以这样做:
//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/>');
});