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

时间:2016-04-18 17:06:41

标签: 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/>');
});
</script>

2 个答案:

答案 0 :(得分:0)

检查此示例

http://api.jquery.com/wrap/

<!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/>');

});