3 回答
TA贡献1809条经验 获得超8个赞
您可以使用DataController#stringify使用getSelectedContent将文档片段中的 HTML 字符串化
import getSelectedContent from "@ckeditor/ckeditor5-engine/src/model/utils/getselectedcontent";
export default class CK5Utils{
static getSelectedHtml(ed) {
const {model, data, model:{document:{selection}}} = ed;
const range = selection.getFirstRange();
if (range.end.isEqual(range.start)) {
return '';
}
const selected = getSelectedContent(model, selection);
return data.stringify(selected);
}
}
TA贡献1951条经验 获得超3个赞
按照 Alexandros Kyriakos 的建议,使用DataController#stringify和getSelectedContent,也可以这样做:
let sHtmlSelection = this.editor.data.stringify(this.editor.model.getSelectedContent(this.editor.model.document.selection));
TA贡献1776条经验 获得超12个赞
您可以抓取某个范围内的选定文本,但要获取 HTML,就有点棘手了。
我能够抓住 thename
并parent
通过switch
语句运行该值。
注意:下面的代码已从此处改编:“在 CKEDITOR 5 中获取突出显示/选定的文本”
const resultArea = document.querySelector('.selected');
let globalEditor;
ClassicEditor
.create(document.querySelector('#editor'))
.then(editor => globalEditor = editor)
.catch(error => console.error(error));
const formatNode = (node) => {
switch (node.parent.name) {
case 'heading1' : return `<h1>${node.data}</h1>`;
case 'heading2' : return `<h2>${node.data}</h2>`;
case 'heading3' : return `<h3>${node.data}</h3>`;
case 'paragraph' : return `<p>${node.data}</p>`;
default : return '';
}
};
const getSelectedHTML = (editor) =>
[...editor.model.document.selection.getFirstRange().getItems()]
.filter(node => node.data)
.map(formatNode)
.join('\n');
document.querySelector('.btn').addEventListener('click', e => {
resultArea.value = getSelectedHTML(globalEditor);
});
<!-- https://cdn.ckeditor.com/#ckeditor5 -->
<script src="https://cdn.ckeditor.com/ckeditor5/23.1.0/classic/ckeditor.js"></script>
<div id="editor">
<h1>This is a heading</h1>
<p>This is some sample content.</p>
</div>
<p>
<button class="btn">Get Selected HTML</button>
</p>
<textarea class="selected" rows="8" cols="72"></textarea>
添加回答
举报