3 回答

TA貢獻(xiàn)1809條經(jīng)驗(yàn) 獲得超8個(gè)贊
您可以使用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貢獻(xiàn)1951條經(jīng)驗(yàn) 獲得超3個(gè)贊
按照 Alexandros Kyriakos 的建議,使用DataController#stringify和getSelectedContent,也可以這樣做:
let?sHtmlSelection?=?this.editor.data.stringify(this.editor.model.getSelectedContent(this.editor.model.document.selection));

TA貢獻(xiàn)1776條經(jīng)驗(yàn) 獲得超12個(gè)贊
您可以抓取某個(gè)范圍內(nèi)的選定文本,但要獲取 HTML,就有點(diǎn)棘手了。
我能夠抓住 thename
并parent
通過switch
語句運(yùn)行該值。
注意:下面的代碼已從此處改編:“在 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>
添加回答
舉報(bào)