首頁 > web前端 > js教程 > 輸入文本選擇代碼段

輸入文本選擇代碼段

Lisa Kudrow
發布: 2025-02-23 09:38:14
原創
694 人瀏覽過

>本文檔提供了用於管理輸入字段中文本選擇的代碼段。 現代鉻和Firefox使用.setSelectionRange(),但是Firefox要求該元素事先具有焦點。

Input Text Selection Code Snippets

獲得光標位置:

jQuery.fn.getCursorPosition = function(){
    if(this.length == 0) return -1;
    return $(this).getSelectionStart();
};
登入後複製

獲得選擇開始:

jQuery.fn.getSelectionStart = function(){
    if(this.length == 0) return -1;
    input = this[0];
    var pos = input.value.length;
    if (input.createTextRange) {
        var r = document.selection.createRange().duplicate();
        r.moveEnd('character', input.value.length);
        if (r.text == '') pos = input.value.length;
        pos = input.value.lastIndexOf(r.text);
    } else if(typeof(input.selectionStart)!="undefined") pos = input.selectionStart;
    return pos;
};
登入後複製

設置光標位置:

jQuery.fn.setCursorPosition = function(pos) {
  this.each(function(index, elem) {
    if (elem.setSelectionRange) {
      elem.setSelectionRange(pos, pos);
    } else if (elem.createTextRange) {
      var range = elem.createTextRange();
      range.collapse(true);
      range.moveEnd('character', pos);
      range.moveStart('character', pos);
      range.select();
    }
  });
  return this;
};
登入後複製

設置光標位置(替代):>

function setCursorPos(node,pos){
    var node = (typeof node == "string" || node instanceof String) ? document.getElementById(node) : node;
    node.focus(); // Crucial for Firefox
    if(!node) return false;
    else if(node.createTextRange){
        var textRange = node.createTextRange();
        textRange.collapse(true);
        textRange.moveStart('character', pos);
        textRange.moveEnd('character', 0);
        textRange.select();
        return true;
    }else if(node.setSelectionRange){
        node.setSelectionRange(pos,pos);
        return true;
    }
    return false;
}
登入後複製

>常見問題: FAQ部分提供了清晰的解釋,

,瀏覽器兼容性和參數的處理。 答案簡潔明了。 這裡不需要更改。 setSelectionRange>

以上是輸入文本選擇代碼段的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板