获取 CKEditor 5 中当前选定的元素



我正在创建一个CKEditor 5插件,用于向任意元素添加id属性。我从图像的TextAlternative插件中获得了很多灵感(如果你不熟悉它是如何工作的,我会看看。

我收到以下错误:Cannot read property 'is' of null

作为我的 UI 课程的一部分,我有以下内容:

if ( !this._isInBalloon ) {
this._balloon.add( {
view: this._form,
position: getBalloonPositionData( editor )
} );
}

getBalloonPositionData是:

/**
* Returns the positioning options that control the geometry of the
* {@link module:ui/panel/balloon/contextualballoon~ContextualBalloon contextual balloon} with respect
* to the selected element in the editor content.
*
* @param {module:core/editor/editor~Editor} editor The editor instance.
* @returns {module:utils/dom/position~Options}
*/
export function getBalloonPositionData( editor ) {
const editingView = editor.editing.view;
const defaultPositions = BalloonPanelView.defaultPositions;
const t = editor.model.document.selection.getSelectedElement(); // ISSUE STARTS HERE
return {
target: editingView.domConverter.viewToDom( t ),
positions: [
defaultPositions.northArrowSouth,
defaultPositions.northArrowSouthWest,
defaultPositions.northArrowSouthEast,
defaultPositions.southArrowNorth,
defaultPositions.southArrowNorthWest,
defaultPositions.southArrowNorthEast
]
};
}

该行:const t = editor.model.document.selection.getSelectedElement();是问题开始的地方。这种获取选定元素的方法取自其他地方,我已经看到它在许多其他插件中使用。

我已经选择了不同的"元素"进行了测试,并且它总是被分配null.

完整的代码在分支feature/add-id-attributes-to-elements上提供@https://github.com/rhysstubbs/ckeditor5-build-classic。

任何帮助都会很棒,TIA。

根据文档,它说如果选择范围包含 0 个或超过 1 个节点(元素(,getSelectedElement 返回 null。这可能会导致您的问题。

最新更新