Come si ottiene la posizione del punto di inserimento in una utilizzando JavaScript?
Ad esempio: This is| a text
This is| a text
Questo dovrebbe restituire 7
.
Come faresti a restituire le stringhe che circondano il cursore / la selezione?
Ad esempio: 'This is', '', ' a text'
.
Se la parola “è” è evidenziata, allora restituisce 'This ', 'is', ' a text'
.
Con Firefox, Safari (e altri browser basati su Gecko) puoi facilmente usare textarea.selectionStart, ma per IE non funziona, quindi dovrai fare qualcosa del genere:
function getCaret(node) { if (node.selectionStart) { return node.selectionStart; } else if (!document.selection) { return 0; } var c = "\001", sel = document.selection.createRange(), dul = sel.duplicate(), len = 0; dul.moveToElementText(node); sel.text = c; len = dul.text.indexOf(c); sel.moveStart('character',-1); sel.text = ""; return len; }
( completo codice qui )
Ti consiglio anche di controllare il plugin jQuery FieldSelection , ti permette di farlo e molto altro …
Modifica: ho effettivamente re-implementato il codice sopra:
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; }
Guarda un esempio qui .
Aggiornato il 5 settembre 2010
Visto che tutti sembrano essere indirizzati qui per questo problema, aggiungo la mia risposta a una domanda simile, che contiene lo stesso codice di questa risposta, ma con lo sfondo completo per coloro che sono interessati:
Document.selection.createRange di IE non include linee vuote iniziali o finali
Tenere conto delle interruzioni di riga finali è complicato in IE e non ho visto nessuna soluzione che funzioni correttamente, comprese altre risposte a questa domanda. È ansible, tuttavia, utilizzare la seguente funzione, che ti restituirà l’inizio e la fine della selezione (che sono gli stessi nel caso di un segno di omissione) all’interno di o di testo
.
Si noti che l’area di testo deve avere lo stato attivo affinché questa funzione funzioni correttamente in IE. In caso di dubbio, prima chiama il metodo focus()
della textarea.
function getInputSelection(el) { var start = 0, end = 0, normalizedValue, range, textInputRange, len, endRange; if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") { start = el.selectionStart; end = el.selectionEnd; } else { range = document.selection.createRange(); if (range && range.parentElement() == el) { len = el.value.length; normalizedValue = el.value.replace(/\r\n/g, "\n"); // Create a working TextRange that lives only in the input textInputRange = el.createTextRange(); textInputRange.moveToBookmark(range.getBookmark()); // Check if the start and end of the selection are at the very end // of the input, since moveStart/moveEnd doesn't return what we want // in those cases endRange = el.createTextRange(); endRange.collapse(false); if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) { start = end = len; } else { start = -textInputRange.moveStart("character", -len); start += normalizedValue.slice(0, start).split("\n").length - 1; if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) { end = len; } else { end = -textInputRange.moveEnd("character", -len); end += normalizedValue.slice(0, end).split("\n").length - 1; } } } } return { start: start, end: end }; }
Ho modificato la funzione di cui sopra per tenere conto dei ritorni a capo in IE. Non è stato testato ma ho fatto qualcosa di simile nel mio codice, quindi dovrebbe essere praticabile.
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); var add_newlines = 0; for (var i=0; i
Se non è necessario supportare IE, è ansible utilizzare selectionStart
e selectionEnd
attributi di textarea
.
Per ottenere la posizione del punto di inserimento, utilizzare selectionStart
:
function getCaretPosition(textarea) { return textarea.selectionStart }
Per ottenere le stringhe che circondano la selezione, utilizzare il seguente codice:
function getSurroundingSelection(textarea) { return [textarea.value.substring(0, textarea.selectionStart) ,textarea.value.substring(textarea.selectionStart, textarea.selectionEnd) ,textarea.value.substring(textarea.selectionEnd, textarea.value.length)] }
Demo su JSFiddle .
Vedi anche i documenti HTMLTextAreaElement .