gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:30:40 26 4
gpt4 key购买 nike

在 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>

如下代码片段,它将文本从 0 传递到单击节点的末尾。但我还需要 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() );
});

我期望结果如下:

 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"

如何在我的 contentEditable-DIV 中获取 HTML 代码而不是文本?提前致谢。

最佳答案

您可以选择 div 并使用其属性 innerHTML

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);
});

关于javascript - 如何在 contentEditable-DIV 中获取 HTML 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26379500/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com