【问题标题】:getSelection on DIV contentEditable获取 DIV 内容上的选择可编辑
【发布时间】:2010-04-26 12:10:04
【问题描述】:

我正在尝试实现项目,我必须在 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(例如&lt;u&gt;,或&lt;span style="color:#AB1;"&gt;
  • tagEnd(例如&lt;/u&gt;,或&lt;/span&gt;
  • id(这里是idExample

我知道在Textarea 上获得选择,但setSelectionRange().selectionStart.selectionEnd 仅适用于textbox (XUL)、input (XHTML) 或textarea (XHTML)。

我能做些什么呢?

【问题讨论】:

  • 您必须使用自己的插件这一事实并不能真正强迫您自己编写所见即所得的编辑器。 CKEditor 和 TinyMCE 允许使用您自己的插件,实际上它们是围绕一个核心构建的一组插件。

标签: javascript editor wysiwyg selection


【解决方案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

【讨论】:

    猜你喜欢
    • 2019-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 2018-03-02
    • 2021-03-09
    • 1970-01-01
    相关资源
    最近更新 更多