首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >getSelection on DIV contentEditable

getSelection on DIV contentEditable
EN

Stack Overflow用户
提问于 2010-04-26 12:10:04
回答 1查看 3.9K关注 0票数 3

我正在努力实现项目,我必须在JavaScript中做一个WYSIWYG编辑器。我不能使用现有的编辑器,因为我需要使用我的插件(例如colorPickerimagePicker)。

现在我有了这个HTML:

代码语言:javascript
复制
<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)。

我能做些什么呢?

EN

回答 1

Stack Overflow用户

发布于 2012-07-29 23:10:41

这是我使用的代码。因为几个月前我在这里发现了它,所以我不能把它归功于它。不记得在哪了。希望它对你有用。

代码语言:javascript
复制
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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2713270

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档