Dal momento che in realtà davvero bisogno di questo soluzione standard e la soluzione di base tipica (mette a fuoco l'input, quindi imposta il valore uguale a) non funziona nel cross-browser, ho dedicato un po 'di tempo a modificare e modificare tutto per farlo funzionare. Basandosi sul codice @kd7 ecco cosa mi è venuto in mente.
Divertiti!Lavori in IE6 +, Firefox, Chrome, Safari, Opera
Cross-browser caret positioning technique (example: moving the cursor to the END)
// ** USEAGE ** (returns a boolean true/false if it worked or not)
// Parameters (Id_of_element, caretPosition_you_want)
setCaretPosition('IDHERE', 10); // example
La carne e le patate è fondamentalmente @KD7 s' setCaretPosition, con la più grande Tweak essendo if (el.selectionStart || el.selectionStart === 0)
, in Firefox la selectionStart è a partire da , che in booleano ovviamente si sta trasformando in False, quindi si è interrotto lì.
In Chrome il più grande problema era che solo dando .focus()
non è stato sufficiente (ha mantenuto selezionando tutto il testo!) Quindi, abbiamo impostato il valore di per sé, a sé el.value = el.value;
prima di chiamare la nostra funzione, ed ora ha una presa & posizione con l'input per utilizzare selectionStart.
function setCaretPosition(elemId, caretPos) {
var el = document.getElementById(elemId);
el.value = el.value;
//^this is used to not only get "focus", but
// to make sure we don't have it everything -selected-
// (it causes an issue in chrome, and having it doesn't hurt any other browser)
if (el !== null) {
if (el.createTextRange) {
var range = el.createTextRange();
range.move('character', caretPos);
range.select();
return true;
}
else {
// (el.selectionStart === 0 added for Firefox bug)
if (el.selectionStart || el.selectionStart === 0) {
el.focus();
el.setSelectionRange(caretPos, caretPos);
return true;
}
else { // fail city, fortunately this never happens (as far as I've tested) :)
el.focus();
return false;
}
}
}
}
questo non è un duplicato, uno richiede jQuery l'altro non vuol – Isaac
@Isaac ho votato a riaprire questo. Tieni presente che SO ha un sacco di piccoli mod che non si preoccupano di altro che di un editing cieco per scopi egoistici. – John