JQ 获取 input 当前光标的位置并插入文字

今天遇到一个需求,当用户在输入框中输入文本的时候,点击一个按钮,获取当前输入框中光标的位置,并在当前位置中插入对应的文字或字符。
简单整理了一下代码:

<input id="title" name="title" type="text" value=""  />
<button id="button">按钮</button>

js代码:

$(function() {
    
    
        $.fn.extend({
    
     
            insertAtCaret: function (myValue) {
    
     
                var $t = $(this)[0]; 
                if (document.selection) {
    
     
                    this.focus(); 
                    sel = document.selection.createRange(); 
                    sel.text = myValue; 
                    this.focus(); 
                } else if ($t.selectionStart || $t.selectionStart == '0') {
    
     
                    var startPos = $t.selectionStart; 
                    var endPos = $t.selectionEnd; 
                    var scrollTop = $t.scrollTop; 
                    $t.value = $t.value.substring(0, startPos) + myValue + $t.value.substring(endPos, $t.value.length); 
                    this.focus(); 
                    $t.selectionStart = startPos + myValue.length; 
                    $t.selectionEnd = startPos + myValue.length; 
                    $t.scrollTop = scrollTop; 
                } else {
    
     
                    this.value += myValue; 
                    this.focus(); 
                } 
            } 
        }) 

        $('#button').on('click', function() {
    
    
          $("#title").insertAtCaret("ABC"); 
        })

      })

测试可以实现该功能。

猜你喜欢

转载自blog.csdn.net/joe0235/article/details/130215778