Come ottenere la posizione del testo selezionata da textarea in JavaScript?


20

Voglio ottenere la posizione del testo selezionata usando JavaScript. Ad esempio,
ho una semplice textarea.

#input-text {
  resize: none;
  width: 50%;
  height: 50px;
  margin: 1rem auto;
}
<textarea id="input-text">I am a student and I want to become a good person</textarea>

Nella mia area di testo, ho alcuni testi come:

"I am a student and I want to become a good person"

Da questa stringa, se seleziono "diventa una brava persona" dalla textarea,
come posso ottenere la posizione del testo / stringa selezionata in javascript?


Qui il carattere di stringa selezionato inizia da 29 e termina in 49. Quindi la posizione iniziale è 29 e la posizione finale è 49


1
Per posizione intendi qual è l'indice del carattere "b" di "diventa" nella stringa?
sabato

Mi sembra che la domanda sia solo per HTMLInputElement.selectionStart e selectionEnd, mentre le risposte parlano principalmente dell'evento di selezione. Non ha senso scrivere una risposta inclusa in tutte le altre risposte.
JollyJoker,

Risposte:


24

Questo funzionerà per la selezione del testo con il mouse e la tastiera per tutti gli elementi textarea sulla pagina. Assicurati di cambiare il selettore e di essere più specifico lì e leggi i commenti se non vuoi / hai bisogno della selezione da tastiera.

var mySelection = function (element) {
    let startPos = element.selectionStart;
    let endPos = element.selectionEnd;
    let selectedText = element.value.substring(startPos, endPos);

    if(selectedText.length <= 0) {
      return; // stop here if selection length is <= 0
    }
    
    // log the selection
    console.log("startPos: " + startPos, " | endPos: " + endPos );
    console.log("selectedText: " +  selectedText);

  };

var textAreaElements = document.querySelectorAll('textarea');
[...textAreaElements].forEach(function(element) {
    // register "mouseup" event for the mouse
    element.addEventListener('mouseup', function(){
        mySelection(element)
    });
    
    // register "keyup" event for the keyboard
    element.addEventListener('keyup', function( event ) {
        // assuming we need CTRL, SHIFT or CMD key to select text
        // only listen for those keyup events
        if(event.keyCode == 16 || event.keyCode == 17 || event.metaKey) {
            mySelection(element)
        }
    });
});
textarea {
   resize: none; 
   width: 50%;
   height: 50px; 
   margin: 1rem auto;
}
<textarea>I am a student and I want to become a good person</textarea>


2
Piuttosto pulito. +1
Saharsh,

2
Questo non si attiva se si seleziona utilizzando la tastiera anziché il mouse.
curiousdannii,

1
@curiousdannii Ho aggiornato la risposta, ora funziona anche con la selezione della tastiera
caramba,

5

Vorrei utilizzare l' evento onselect per ottenere lo stesso.

<textarea id="input-text" onselect="myFunction(event)">I am a student and I want to become a good person</textarea>


<script>
    function myFunction(event) {
      const start  = event.currentTarget.selectionStart;
      const end= event.currentTarget.selectionEnd;
    }
</script>

1
    var idoftextarea='answer';
    function getSelectedText(idoftextarea){
        var textArea = document.getElementById(idoftextarea);
        var text =textArea.value;
        var indexStart=textArea.selectionStart;
        var indexEnd=textArea.selectionEnd;
        alert(text.substring(indexStart, indexEnd));

    }


    getSelectedText(idoftextarea);


1

La risposta di Caramba ha funzionato piuttosto bene, tuttavia ho avuto il problema che se hai selezionato del testo e rilasciato il mouse al di fuori dell'area di testo, l'evento non si è attivato.

Per risolvere questo, ho cambiato l'evento iniziale in mousedown, questo evento registra un mouseupevento sul documento per assicurarsi che si attivi dopo che il cursore è stato rilasciato. L' mouseupevento quindi si rimuove dopo che è stato generato.

Ciò può essere ottenuto aggiungendo l' onceopzione a addEventListener, ma purtroppo non è supportato in IE11, motivo per cui ho usato la soluzione nello snippet.

var mySelection = function (element) {
    let startPos = element.selectionStart;
    let endPos = element.selectionEnd;
    let selectedText = element.value.substring(startPos, endPos);

    if(selectedText.length <= 0) {
      return; // stop here if selection length is <= 0
    }
    
    // log the selection
    console.log("startPos: " + startPos, " | endPos: " + endPos );
    console.log("selectedText: " +  selectedText);
};

function addSelfDestructiveEventListener (element, eventType, callback) {
    let handler = () => {
        callback();
        element.removeEventListener(eventType, handler);
    };
    element.addEventListener(eventType, handler);
};

var textAreaElements = document.querySelectorAll('textarea');
[...textAreaElements].forEach(function(element) {
    // register "mouseup" event for those
    element.addEventListener('mousedown', function(){
      // This will only run the event once and then remove itself
      addSelfDestructiveEventListener(document, 'mouseup', function() {
        mySelection(element)
      })
    });
    
    // register "keyup" event for the keyboard
    element.addEventListener('keyup', function( event ) {
        // assuming we need CTRL, SHIFT or CMD key to select text
        // only listen for those keyup events
        if(event.keyCode == 16 || event.keyCode == 17 || event.metaKey) {
            mySelection(element)
        }
    });
});
textarea {
   resize: none; 
   width: 50%;
   height: 50px; 
   margin: 1rem auto;
}
<textarea>I am a student and I want to become a good person</textarea>


Mi piace come hai implementato il addSelfDestructiveEventListener!
Caramba,

0
var mySelection = function (element) {
let startPos = element.selectionStart;
let endPos = element.selectionEnd;
let selectedText = element.value.substring(startPos, endPos);

if(selectedText.length <= 0) {
  return; // stop here if selection length is <= 0
}

// log the selection
console.log("startPos: " + startPos, " | endPos: " + endPos );
console.log("selectedText: " +  selectedText); };var textAreaElements = document.querySelectorAll('textarea'); 
[...textAreaElements].forEach(function(element) {
// register "mouseup" event for the mouse
element.addEventListener('mouseup', function(){
    mySelection(element)
});
// register "keyup" event for the keyboard
element.addEventListener('keyup', function( event ) {
    // assuming we need CTRL, SHIFT or CMD key to select text
    // only listen for those keyup events
    if(event.keyCode == 16 || event.keyCode == 17 || event.metaKey) {
        mySelection(element)
    }
});});

Potete per favore aggiungere una piccola spiegazione a ciò che il codice fa?
Rachel McGuigan il
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.