【问题标题】:get and set cursor position in content editable div获取和设置内容可编辑 div 中的光标位置
【发布时间】:2020-05-10 16:04:24
【问题描述】:

在内容可编辑的 div 中,我希望获取和设置光标位置,但不考虑子元素(例如 等)。

为了得到,我找到了这个解决方案:Get a range's start and end offset's relative to its parent container

但是对于设置,我不知道。

拜托,你能帮帮我吗?

谢谢你

【问题讨论】:

    标签: javascript cursor contenteditable


    【解决方案1】:

    你可以使用rangy自己定义,就像这样:

    var selector = document.querySelector('[contenteditable]');
    
    var setCaretIndex = function (index) {
        var charIndex = 0, stop = {};
    
        var traverseNodes = function (node) {
            if (node.nodeType === 3) {
                var nextCharIndex = charIndex + node.length;
                if (index >= charIndex && index <= nextCharIndex) {
                    rangy.getSelection().collapse(node, index - charIndex);
                    throw stop;
                }
                charIndex = nextCharIndex;
            }
    
            // Count an empty element as a single character. The list below may not be exhaustive.
            else if (node.nodeType === 1 && /^(input|br|img|col|area|link|meta|link|param|base)$/i.test(node.nodeName)) {
                charIndex += 1;
            } else {
                var child = node.firstChild;
                while (child) {
                    traverseNodes(child);
                    child = child.nextSibling;
                }
            }
        };
    
        try {
            traverseNodes(selector);
        } catch (ex) {
            if (ex !== stop) throw ex;
        }
    };
    

    要使用该功能,需要先聚焦编辑器:

    selector.focus();
    

    然后给出一个索引来设置光标位置:

    setCaretIndex(3);
    

    Fiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-05
      • 1970-01-01
      • 1970-01-01
      • 2011-01-13
      • 2016-07-05
      • 2023-01-10
      • 1970-01-01
      相关资源
      最近更新 更多