2011-03-26 59 views
0

我有一个小问题/问题。我在一个小WYSIWYG编辑器上工作。我使用带选项contentEditable =“true”的div,我想知道什么时候点击某个按钮,我的div中的哪个元素正在被用户修改。如何知道哪些元素在contentEditable情况下正在修改?

例如,如果div上有3个段落,并且该用户修改了第二个,我想知道他何时点击他当前要修改第二段以显示文本内容的按钮!在这个例子中“P2”:

<div contenteditable="true"><p>P1</p><p>P2</p><p>P3</p></div> 

在此先感谢您的帮助。

萨科

回答

0

你可以检查在mousedown事件的按钮的选择。以下内容适用于所有主流浏览器:

function getSelectionBoundaryContainerElement(start) { 
    var container = null; 
    if (typeof window.getSelection != "undefined") { 
     var sel = window.getSelection(); 
     if (sel.rangeCount) { 
      var range = sel.getRangeAt(0); 
      range.collapse(start); 
      container = range.startContainer; 
      if (container.nodeType != 1) { 
       container = container.parentNode; 
      } 
     } 
    } else if (typeof document.selection != "undefined" && document.selection.type != "Control") { 
     var textRange = document.selection.createRange(); 
     textRange.collapse(start); 
     container = textRange.parentElement(); 
    } 
    return container; 
} 

document.getElementById("yourButtonId").onmousedown = function() { 
    alert(getSelectionBoundaryContainerElement().innerHTML); 
} 
相关问题