对于我的 draftjs
项目,我希望用户能够插入链接。为此,我在按下快捷键 cmk + k
后创建了一个弹出窗口。
为了更好的用户体验,我目前正在尝试智能对齐弹出窗口。
参见上图,我可以将弹出窗口定位在当前焦点线下方。编辑器容器的边界矩形对象和当前选择的边界矩形将包含足够的信息供我完成计算。
但是,在其他情况下,当只有空行时:
(弹出窗口之前的光标位置是编辑器的末尾)
window.getSelection().getRangeAt(0).getBoundingClientRect()
将返回每个值为 0 的 DOMRect 对象。在 dom 或 draftjs
中是否有任何解决方法> 我可以获得足够的信息来智能对齐弹出窗口吗?因此弹出窗口可能会在当前光标位置周围弹出。
最佳答案
为了解决这个问题,我使用光标的 block 索引乘以行高+一些偏移量来在选择空行时实现从顶部的正确放置。
这是我的“计算弹出窗口位置”函数中的代码。当选择带有文本的行时,我排除了用于获取顶部/左侧位置的部分,而当 getBoundingClientRect() 返回 null 时,当我需要考虑没有文本的行时,我只包含了这些部分。
const singleLineHeightOffset = 28;
const topBlankLineOffset = 15;
let position = getVisibleSelectionRect(window);
// If there is a visible selection area
if (position) {
// Get ref of editor via prop and location of div if exists
let editorRef = forwardedRef;
element = ReactDOM.findDOMNode(editorRef.current) as HTMLElement;
if (element) {
// Code here to calculate when a line with text is selected
} else {
// Else if no text selected on line
// Get current block position of cursor
const currentBlockKey = editorState.getSelection().getStartKey();
const currentBlockIndex = editorState
.getCurrentContent()
.getBlockMap()
.keySeq()
.findIndex((k) => k === currentBlockKey);
let emptyLineTopHeight =
singleLineHeightOffset * (currentBlockIndex + 1) - 5;
// If first line of editor, add offset for toolbar/padding
if (currentBlockIndex === 0) emptyLineTopHeight += topBlankLineOffset;
setTopPosition(emptyLineTopHeight);
}
这将检测空光标所在的行,然后通过乘以行高来创建顶部偏移量。您可能需要像我一样尝试偏移和边缘情况,例如初始线。
关于javascript - 如何获取当前光标在draft.js中的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69534820/