javascript - DIV 内容上的 getSelectionEditable

标签 javascript editor wysiwyg selection

我正在努力实现项目,我必须用 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)。

我能做什么?

最佳答案

这是我使用的代码。自从几个月前我在 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

关于javascript - DIV 内容上的 getSelectionEditable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2713270/

相关文章:

javascript - 在 Google Scripts 自定义函数中接受任意数量的参数?

javascript - 通过表单编辑 CSS - 实时预览

graph - Mathematica 图形编辑器?

editor - UDK可以用于非游戏项目吗?

php - 使用 php 保护简单所见即所得的最佳方法

javascript - 适用于 chrome ext 的简单且流行的 javascript 框架。发展

Javascript 混合内存地址? (重置数组不起作用)

javascript - WYSIWYG javascript 编辑器可用于论坛吗?

javascript - 使用 draft.js 是否可以使用类名创建自定义 block 跨度

javascript - 按 "Enter"键实现新换行