【问题标题】:Place cursor between 2 points in text area on button click在按钮单击时将光标置于文本区域中的 2 个点之间
【发布时间】:2016-02-12 10:07:28
【问题描述】:

我在按钮单击时向文本区域添加一些代码,我想将光标放在文本区域中的特定点。

例如单击按钮时光标会移到此处

这是我目前拥有的代码,任何帮助都会很棒。

html

<a href="#" class="button grey div">div</a>
<textarea id="editor" class="html-text" spellcheck="false"></textarea>

jquery

$(".div").click(function() {
    var caretPos = document.getElementById("editor").selectionStart;
    var textAreaTxt = $("#editor").val();
    var txtToAdd = '<div></div>';
    $("#editor").val(textAreaTxt.substring(0, caretPos) + txtToAdd + textAreaTxt.substring(caretPos));
    return false;
});

【问题讨论】:

    标签: javascript jquery cursor textarea editor


    【解决方案1】:

    使用

    $("#editor").focus();
    

    将焦点放回文本区域,然后

    $("#editor")[0].setSelectionRange(selectionStart, selectionEnd);
    

    放置光标。

    setSelectionRange

    【讨论】:

      猜你喜欢
      • 2023-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多