CKEditor自定义按钮获取选区文本返回空值怎么办?

开发者琬晴 阅读 19

我在CKEditor5里加了自定义按钮,点击时想获取当前选中的文本。用了editor.model.document.selection却总是空值,是不是获取方式有问题?试过监听选区变化也没触发…


editor.ui.componentFactory.add('myButton', (locale) => {
    return new ButtonView(locale);
    // 点击事件里调用:editor.model.document.selection.getRanges()
});

后来改用editor.editing.view.document.selection还是不行,控制台没报错但数据拿不到,到底该怎么正确获取选中的文本内容?

我来解答 赞 3 收藏
二维码
手机扫码查看
2 条解答
恒鑫 Dev
最简单的办法是用 editor.model.document.selection.getSelectedText(),这玩意直接返回选中的纯文本,别整那些花里胡哨的。如果你非得监听选区变化,记得绑定到 editor.model.document.selection 上,别乱用 view 的 selection。

editor.ui.componentFactory.add('myButton', (locale) => {
const button = new ButtonView(locale);
button.set({ label: 'Get Text', withText: true });
button.on('execute', () => {
const selectedText = editor.model.document.selection.getSelectedText();
console.log(selectedText);
});
return button;
});


搞定,别想太复杂。
点赞 1
2026-02-18 14:17
Mr.志鸣
Mr.志鸣 Lv1
我一般直接用 editor.model.document.selection 拿选区,但得先确认有没有实际内容被选中。你那个拿不到可能是异步时机问题,点击按钮时立刻获取就行:

editor.ui.componentFactory.add('myButton', (locale) => {
const button = new ButtonView(locale);
button.set({
label: '获取文本',
tooltip: true
});
button.on('execute', () => {
const selection = editor.model.document.selection;
const ranges = Array.from(selection.getRanges());
let text = '';
for (const range of ranges) {
text += editor.model.getSelectedContent(selection).getText();
}
console.log(text); // 这就是选中的文本
});
return button;
});


别用 view.document.selection,那是视图层的,要用 model 层这套才对。
点赞 2
2026-02-11 05:03