获取元素在contenteditable中被更改

时间:2016-03-13 23:51:57

标签: javascript html html5

如何获取正在编辑的元素?

HTML

<div contenteditable=true>
  <pre>
    <span class="1">First line</span>
    <span class="2">Second line</span>
  </pre>
</div>

当我正在编辑&#34;第一行&#34;时,如何查看正在编辑的跨栏类?

JS

window.addEventListener("input", inputHandler, false);
function inputHandler(e) {
  console.log(e.target);
}

打印出整个div类:

<div contenteditable=true>
  <pre>
    <span class="1">First line</span>
    <span class="2">Second line</span>
  </pre>
</div>

但我只想获得<span class="1">First line</span>

2 个答案:

答案 0 :(得分:4)

Span element无法input/keypress/keyup ... events,而events无法注册DOMCharacterDataModified。虽然还有其他方法可以实现此目的,但您可以使用var div = document.getElementById("edit"); div.addEventListener("DOMCharacterDataModified", inputHandler, false); function inputHandler(e) { var elem = e.target.parentNode; alert("Element: " + elem.tagName + " class name: " + elem.className); }事件,请检查下面的代码段

&#13;
&#13;
<div id="edit" contenteditable=true>
  <pre>
    <span class="1">First line</span>
    <span class="2" >Second line</span>
  </pre>
</div>
&#13;
rwx
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您必须单独影响您计划修改的每件作品的class Dog { int age; public Dog(int dogsAge) { age = dogsAge; } public void bark() { System.out.println("Woof!"); } public void run(int feet){ System.out.println("Your dog ran " + feet + " feet!"); } public int getAge() { return age; } public static void main(String[] args) { Dog spike = new Dog(1); spike.bark(); spike.run(100); int spikeAge = spike.getAge(); System.out.println(spikeAge); //System.out.println(spike.age); } } 属性 您必须选择如何向所有这些添加事件侦听器。例如,像这样:

contenteditable
var editables = document.getElementsByClassName('editable');
for (var editable of editables) {
  editable.addEventListener("input", inputHandler, false);
}
function inputHandler(e) {
  console.log(e.target);
}