简体   繁体   English

如何在contentEditable-DIV中获取HTML代码

[英]How can I get HTML-Code in a contentEditable-DIV

In a contentEditable-DIV I try to get the HTML-Code from strat-Position 0 to end-position where the user has clicked. 在contentEditable-DIV中,我尝试将HTML代码从strat-Position 0转到用户单击的最终位置。

<div id="MyEditableId" contentEditable="true">
  1. Some text 123. <span style="background-color: #0CF;">text 123</span> 456 <span style="background-color: #9F3;">2-> abc </span>
    <br />
    <p> E.g. here is clicked: "click" Text after click </p>
    <p></p>
    <br />
    end of text.
</div>

Something as below code snippet, which delivers the text from 0 to end of clicked node. 下面的代码段,将文本从0传递到被单击节点的末尾。 But I need also the HTML-Code in contentEditable-DIV. 但是我还需要contentEditable-DIV中的HTML代码。

$('#MyEditableId').on('mouseup', function(event) {
    var MyEditable = document.getElementById('MyEditableId');
    MyEditable.focus();
    range = document.createRange();

    // endOffset: It will be better the length of where actually was clicked, e.g. after 15-characters. But this.length will be also ok.
    endOffset = $(this).length;
    range.setStart(MyEditable.firstChild,0);
    range.setEnd(event.target,endOffset);
    var selection = window.getSelection();
    selection.addRange(range);

    // Below I get the selected text from 0 to end of clicked node. But I need the selected HTML-Code from 0 to end of clicked position.
    alert( window.getSelection() );
});

I expect for the result something as follows: 我期望结果如下:

 1. Some text 123. <span style="background-color: #0CF;">text 123</span> 456 <span style="background-color: #9F3;">2-> abc </span>
    <br />
    <p> E.g. here is clicked: "click"

How can I get the HTML-Code instead of text in my contentEditable-DIV? 如何在我的contentEditable-DIV中获取HTML代码而不是文本? Thanks In Advance. 提前致谢。

You can select the div and use its property innerHTML 您可以选择div并使用其属性innerHTML

http://jsfiddle.net/at917rss/ http://jsfiddle.net/at917rss/

<div id="MyEditableId" contentEditable="true">
  1. Some text 123. <span style="background-color: #0CF;">text 123</span> 456 <span style="background-color: #9F3;">2-> abc </span>
    <br />
    <p> E.g. here is clicked: "click" Text after click </p>
    <p></p>
    <br />
    end of text.
</div>

    $('#MyEditableId').on('mouseup', function(event) {
        var MyEditable = document.getElementById('MyEditableId');
        MyEditable.focus();
        range = document.createRange();

        // endOffset: It will be better the length of where actually was clicked, e.g. after 15-characters. But this.length will be also ok.
        endOffset = $(this).length;
        range.setStart(MyEditable.firstChild,0);
        range.setEnd(event.target,endOffset);
        var selection = window.getSelection();
        selection.addRange(range);

        // get html for your div  
        var myDiv = document.getElementById('MyEditableId');
        alert(myDiv.innerHTML);
    });

只需将代码中的警报行更改为下面的行即可。

alert($.trim($('<div>').append(range.cloneContents()).html()));

I was just going through the documentation for Range and selection . 我只是浏览Rangeselection的文档。 You could use the extractContents() or cloneContents() method supported by the Range object like so in your case Demo : 您可以使用Range对象支持的extractContents()cloneContents()方法,例如您的Demo

 var fragment = window.getSelection().getRangeAt(0).extractContents();

This automatically gets the first range that the user has selected. 这将自动获取用户选择的第一个范围。 Although users can select multiple ranges by holding down the "Ctrl" Key. 尽管用户可以通过按住“ Ctrl”键选择多个范围。 This gives the exact match till the cursor position for the simpler cases. 对于更简单的情况,这将给出精确的匹配,直到光标位置为止。

There are some caveats to this though. 尽管有一些注意事项。 Both the methods extractContents() or cloneContents() return a documentFragment and the documentation clearly states that: 方法extractContents()cloneContents()返回documentFragment ,并且文档明确指出:

Event Listeners added using DOM Events are not copied during cloning. 使用DOM事件添加的事件侦听器在克隆过程中不会被复制。 HTML attribute events are duplicated as they are for the DOM Core cloneNode method. HTML属性事件与DOM Core cloneNode方法一样被复制。 HTML id attributes are also cloned, which can lead to an invalid document through cloning. HTML id属性也将被克隆,这可能导致通过克隆导致无效的文档

In essence, document fragments can contain invalid HTML and therefore you can not use all the normal DOM like .html() in some cases. 本质上,文档片段可以包含无效的HTML ,因此在某些情况下,您不能使用所有普通的DOM例如.html()

I found a relevant SO post on getting the cursor position on a contentEditable element and came across a TextRange Object (supported in IE < 9) and it has an htmlText property which returns the HTML source of the selection as a 'valid' HTML fragment. 我找到了一条相关的SO帖子,内容关于如何将光标放在contentEditable元素上,并遇到了TextRange对象 (在IE <9中受支持),并且它具有htmlText属性,该属性将所选内容的HTML源作为“有效” HTML片段返回。 So in that case you would do something like: 因此,在这种情况下,您将执行以下操作:

 var fragment = document.selection.createTextRange().htmlText;

However since most of the modern browsers support Window.getSelection() , it's good practice that you use it and build upon the suitable methods you have at your disposal. 但是,由于大多数现代浏览器都支持 Window.getSelection() ,因此,最好使用它并以Window.getSelection()的合适方法为基础。 Hope it gets you started in the right direction. 希望它能帮助您朝正确的方向开始。

Sidenote - Also from the docs : 旁注 -同样来自docs

using a selection object as the argument to window.alert will call the object's toString method 使用选择对象作为window.alert的参数,将调用该对象的toString方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM