【问题标题】:contenteditable: save and restore caret positioncontenteditable:保存和恢复插入符号位置
【发布时间】:2017-09-17 01:41:53
【问题描述】:

下面的函数使插入符号移回开头。调用函数后如何让它保持在同一个位置?

function highlightText() {
            var mystring = document.getElementById("writeArea").textContent;
            mystring = mystring.replace(/function/g , "<span class=\"func\">function</span>");
            document.getElementById("writeArea").innerHTML = mystring;
        }

Contenteditable 声明:

<div class="codeArea" id="writeArea" contenteditable="true"> <p> edit me! </p> </div>

【问题讨论】:

    标签: javascript jquery html contenteditable caret


    【解决方案1】:

    使用selectionStart 获取和设置插入符号的位置:

    document.getElementById("writeArea").onkeyup = highlightText(this);
    function highlightText(o) {
      var mystring = document.getElementById("writeArea").textContent,
      caretPosition = o.selectionStart;
      mystring = mystring.replace(/function/g , "<span class=\"func\">function</span>");
      document.getElementById("writeArea").innerHTML = mystring;
      document.getElementById("writeArea").selectionStart = caretPosition;
    }
    &lt;div class="codeArea" id="writeArea" contenteditable="true"&gt; &lt;p&gt; edit me! &lt;/p&gt; &lt;/div&gt;

    【讨论】:

    • 抱歉这个菜鸟问题,但我想为 o 写什么?谷歌浏览器刚刚给了我一个“未捕获的类型错误:无法读取未定义的属性'selectionStart'”的错误。
    • 对您的 contentedi div 的文档对象的引用
    • 我在 reactjs + Chrome 上试过,这不适用于 contenteditable 标签...如果你添加 document.getElementById("writeArea").selectionEnd = caretPosition; 也适用于输入标签
    猜你喜欢
    • 2011-06-02
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 2019-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多