javascript - 如何获取当前光标在draft.js中的位置?

标签 javascript html reactjs next.js draftjs

对于我的 draftjs 项目,我希望用户能够插入链接。为此,我在按下快捷键 cmk + k 后创建了一个弹出窗口。

为了更好的用户体验,我目前正在尝试智能对齐弹出窗口。

enter image description here

参见上图,我可以将弹出窗口定位在当前焦点线下方。编辑器容器的边界矩形对象和当前选择的边界矩形将包含足够的信息供我完成计算。

但是,在其他情况下,当只有空行时: enter image description here (弹出窗口之前的光标位置是编辑器的末尾) 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/

相关文章:

jquery - 如何在轮播 slider 中添加图像之间的间隙或消除滑动时的故障

php - 当从 select 标记触发 onChange 事件时,从 mysql 数据库加载 html 表

javascript - 使用 React(与 Redux)作为网站中的组件

reactjs - 当它在设备上运行时,你如何调试 react-native?

html - React App 在打开 react-signature-canvas 时有时会崩溃

javascript - 检查多维对象是否为空

javascript - 响应式菜单视口(viewport)高度

html - HTML 5 "offline web application"中有哪些新内容尚未在所有浏览器中可用?

javascript - Bootstrap 3 与当前的 AngularJS Bootstrap 指令兼容吗?

javascript - 我可以从另一个上下文的 test.each 标记模板文字中捕获测试吗?