获取DIV contentEditable中的getSelection

3

我正在尝试完成一个项目,需要使用JavaScript实现所见即所得编辑器。由于需要使用自己的插件(例如colorPickerimagePicker),因此无法使用现有的编辑器。

目前,我有以下HTML代码:

<div class="K_editor" id="idExample">
   <div class="K_links">
      <div class="K_editor_link K_editor_linkBold">B</div>
      <div class="K_editor_link K_editor_linkItalic">I</div>
      <div class="K_editor_link K_editor_linkUnderline">U</div>
   </div>
   <iframe width="696" height="212" frameborder="0" src="js/myEditor_iFrame.php">
      <html>
         <head/>
         <body>
            <div id="contentIframe" contenteditable="true">
               This is a test code, with <strong>bold</strong> text and  <em>italic</em> text.
            </div>
         </body>
      </html>
   </iframe>
   <input type="submit"/>
</div>

当点击 .K_editor_link 时,一个带有参数的函数会被打开:

  • tagStart(例如 <u><span style="color:#AB1;">
  • tagEnd(例如 </u></span>
  • id(此处为 idExample

我现在可以在 Textarea 上获取选区,但是 setSelectionRange().selectionStart.selectionEnd 只适用于 textbox(XUL)、input(XHTML)或 textarea(XHTML)。

我该怎么办?


你必须使用自己的插件这一事实并不真正强制你自己编写所见即所得编辑器。CKEditor和TinyMCE允许使用自己的插件,事实上它们是围绕核心构建的一组插件。 - AlfonsoML
1个回答

1

这是我使用的代码。我不能为它负责,因为几个月前我在SO上找到了它。不记得在哪里了。希望它对你有用。

function getSelectionHtml() 
{
    var html = "";

    if (typeof window.getSelection != "undefined") 
        {
        var sel = window.getSelection();
        if (sel.rangeCount) 
            {
            var container = document.createElement("div");
            for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                container.appendChild(sel.getRangeAt(i).cloneContents());
            }
            html = container.innerHTML;
        }
    } else if (typeof document.selection != "undefined") {
        if (document.selection.type == "Text") {
            html = document.selection.createRange().htmlText;
        }
    }
    return html;

}

代码来自于这个问题:window.getSelection返回html


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接