Javascript:如何知道用户在contenteditable div中添加文本的跨度?

时间:2016-04-18 12:02:23

标签: javascript jquery html

如果用户在有问题的div中将wordx放在wordx之前,例如somthingwordx,因为新添加的文本没有包含在任何现有的跨度中,我如何知道用户添加文本的跨度?

演示

<div id="inputbox" style="border:1px solid lightgrey" contenteditable="true">
  <span id="1">word1</span>  <span id="2">word2</span>
  <span id="3">word3</span>  <span id="4">word4</span>  <span id="5">word5</span>  <span id="6">word6</span>  <span id="7">word7</span>  <span id="8">word8</span>  <span id="9">word9</span>  <span id="10">word10</span>  <span id="11">word11</span>  <span id="12">word12</span>
</div>

1 个答案:

答案 0 :(得分:0)

使用DOMCharacterDataModified事件。

&#13;
&#13;
var div = document.getElementById("inputbox");
div.addEventListener("DOMCharacterDataModified", function(e) {
  var elem = e.target.parentNode;
  console.log(elem);
}, false);
&#13;
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
<div id="inputbox" style="border:1px solid lightgrey" contenteditable="true">
  <span id="1">word1</span>  <span id="2">word2</span>
  <span id="3">word3</span>  <span id="4">word4</span>  <span id="5">word5</span>  <span id="6">word6</span>  <span id="7">word7</span>  <span id="8">word8</span>  <span id="9">word9</span>  <span id="10">word10</span>  <span id="11">word11</span>  <span id="12">word12</span>
</div>
&#13;
&#13;
&#13;