开发者

How to get selected text/caret position of an input that doesn't have focus?

开发者 https://www.devze.com 2023-02-14 04:40 出处:网络
Is it possible to (reliably) get the selected text/caret position in a input text box if that field doesn\'t have focus?

Is it possible to (reliably) get the selected text/caret position in a input text box if that field doesn't have focus?

If not, what's the best way to get and retain this data?

Basically, when a user clicks a button I want to insert some text at the caret position. However开发者_如何学运维, as soon as the user clicks that button, the field loses focus and I lose the caret position.


The following script will hold the caret position and then a button click will insert text at the stored position:

Javascript:

<script type="text/javascript">
//Gets the position of the cursor
function getCaret(el) { 
  if (el.selectionStart) { 
    return el.selectionStart; 
  } else if (document.selection) { 
    el.focus(); 

    var r = document.selection.createRange(); 
    if (r == null) { 
      return 0; 
    } 

    var re = el.createTextRange(), 
        rc = re.duplicate(); 
    re.moveToBookmark(r.getBookmark()); 
    rc.setEndPoint('EndToStart', re); 

    return rc.text.length; 
  }  
  return 0; 
}

function InsertText() {
    var textarea = document.getElementById('txtArea');
    var currentPos = getCaret(textarea);
    var strLeft = textarea.value.substring(0,currentPos);
    var strMiddle = "-- Hello World --";
    var strRight = textarea.value.substring(currentPos,textarea.value.length);
    textarea.value = strLeft + strMiddle + strRight;
}
</script>

HTML:

<textarea id="txtArea" >Lorem ipsum dolor sit amet, consectetur adipiscing elit.</textarea>
<button onclick="InsertText();">Insert Text</button>

The script can be modified if you want to hold the caret position in a variable onblur.


Use the following 2 functions to save and restore text selection.

function saveSelection() {
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            return sel.getRangeAt(0);
        }
    } else if (document.selection && document.selection.createRange) {
        return document.selection.createRange();
    }
    return null;
}

function restoreSelection(range) {
    if (range) {
        if (window.getSelection) {
            sel = window.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
        } else if (document.selection && range.select) {
            range.select();
        }
    }
}

Check Working example at http://jsfiddle.net/LhQda/

Type something in the TEXTAREA, then click outside the TEXTAERA to lose the selection, then click on the focus button to restore selection and focus again.

0

精彩评论

暂无评论...
验证码 换一张
取 消