This document provides code snippets for managing text selection in input fields. Modern Chrome and Firefox utilize .setSelectionRange()
, but Firefox requires the element to have focus beforehand.
Getting Cursor Position:
jQuery.fn.getCursorPosition = function(){ if(this.length == 0) return -1; return $(this).getSelectionStart(); };
Getting Selection Start:
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; };
Setting Cursor Position:
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; };
Setting Cursor Position (Alternative):
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; }
Frequently Asked Questions:
The FAQ section provides clear explanations of setSelectionRange
, selectionStart
, selectionEnd
, browser compatibility, and handling of parameters. The answers are concise and accurate. No changes are needed here.
The above is the detailed content of Input Text Selection Code Snippets. For more information, please follow other related articles on the PHP Chinese website!