GetSelection on DIV contentEditable

I am trying to achieve a project and I have to make a WYSIWYG editor in JavaScript. I cannot use an existing editor because I need to use my plugins (e.g., colorPickeror imagePicker).

Now I have this 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>

In the event of an event, click .K_editor_link, the function will open with arguments:

  • tagStart(example <u>or <span style="color:#AB1;">)
  • tagEnd(example </u>or </span>)
  • id(here idExample)

I know that there is a choice in Textarea, but setSelectionRange(), .selectionStartand .selectionEndare intended only for textbox(XUL), input(XHTML) or Textarea(XHTML).

What can I do for this?

+3
source share
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 return html

0

Source: https://habr.com/ru/post/1742811/


All Articles