【问题标题】:How to enter text in a specific place into a textobox when clicking a div单击div时如何将特定位置的文本输入到文本框中
【发布时间】:2018-07-19 09:10:07
【问题描述】:

我有自己的 jquery 键盘,允许用户在单击每个键时在文本框中输入文本。问题是由于我当前的代码,用户无法在单词内的特定位置书写:

HTML:

<input type="text" id="id">

<!--Some keys-->
<div id="k-e" class="key key-btn">e</div>
<div id="k-r" class="key key-btn">r</div>
<div id="k-t" class="key key-btn">t</div>

jquery:

$("div.key").click(function(e){
    var currentName = $("#name").val();
    $("#name").val(currentName + $(this).text());
});

现在,例如:如果用户在“Maia”中的字母“i”之前单击以写入字母“r”,则在单击键时输入的字母是在单词的末尾。

谁能解释我如何使用 jquery 实现这一点?

【问题讨论】:

    标签: jquery


    【解决方案1】:

    我成功使用 JavaScripts selectionStart 在输入中找到当前光标位置。
    然后,我使用jAndy找到here的方法在光标位置插入新文本。

    $("div.key").click(function(e) {
      var current_text = $("#name").val();
      var cursor_position = $("#name")[0].selectionStart;
      var new_text = $(this).text();
      current_text = [current_text.slice(0, cursor_position), new_text, current_text.slice(cursor_position)].join('');
      $("#name").val(current_text);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <input type="text" id="name">
    
    <!--Some keys-->
    <div id="k-e" class="key key-btn">e</div>
    <div id="k-r" class="key key-btn">r</div>
    <div id="k-t" class="key key-btn">t</div>

    【讨论】:

    • 嗯...正在做我需要的,但现在正在向后输入文本。例如:如果我写奥斯卡正在进入拉索。我错过了什么吗?
    • 嗯,我没有看到这种行为。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-08
    • 2014-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-22
    • 1970-01-01
    相关资源
    最近更新 更多