代码之家  ›  专栏  ›  技术社区  ›  Pier

如何使用Slate.js将光标移动到当前行的末尾?

  •  2
  • Pier  · 技术社区  · 6 年前

    onKeyDown (event, change, next) {
    
        if (event.key === 'ArrowRight') {
            if (event.metaKey) {
                event.preventDefault();
                change.moveTo(5);
                return true;
            }
        }
    
        return next();
    }
    

    问题是现在偏移索引是固定的 5 change.moveTo(5)

    如何找到当前行最后一个字符的索引?

    1 回复  |  直到 6 年前
        1
  •  5
  •   Pier    6 年前

    Slate并不真正了解直线之类的东西,所以解决方法是获取一个本地范围并检查其边界框的坐标。

    我做了一个函数,返回一行中最后一个可能位置的索引,或者当前文本块中最后一个位置的索引,如果插入符号在最后一行中,就会出现这种情况。

    getIndexLastCharOfLine () {
        const selection = window.getSelection()
        const range = selection.getRangeAt(0);
        const caretIndex = range.startOffset;
        const rect = range.getBoundingClientRect();
        const container = range.startContainer;
        const lastIndex = container.length;
    
        for (let i = caretIndex; i < lastIndex; i++) {
            const rangeTest = document.createRange();
            rangeTest.setStart(container, i);
            const rectTest = rangeTest.getBoundingClientRect();
            // if the y is different it means the test range is in a different line
            if (rectTest.y !== rect.y) return i - 1;
        }
    
        return lastIndex;
    }