Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

262
Visualizações
Obtener el texto resaltado/seleccionado

¿Es posible obtener el texto resaltado en un párrafo de un sitio web, por ejemplo, usando jQuery?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Obtener el texto que el usuario ha seleccionado es relativamente simple. No se obtiene ningún beneficio al involucrar a jQuery, ya que no necesita nada más que los objetos de la window y el document .

 function getSelectionText() { var text = ""; if (window.getSelection) { text = window.getSelection().toString(); } else if (document.selection && document.selection.type != "Control") { text = document.selection.createRange().text; } return text; }

Si está interesado en una implementación que también trate con selecciones en elementos <textarea> y texty <input> , puede usar lo siguiente. Dado que ahora es 2016, estoy omitiendo el código requerido para la compatibilidad con IE <= 8, pero he publicado cosas para eso en muchos lugares en SO.

 function getSelectionText() { var text = ""; var activeEl = document.activeElement; var activeElTagName = activeEl ? activeEl.tagName.toLowerCase() : null; if ( (activeElTagName == "textarea") || (activeElTagName == "input" && /^(?:text|search|password|tel|url)$/i.test(activeEl.type)) && (typeof activeEl.selectionStart == "number") ) { text = activeEl.value.slice(activeEl.selectionStart, activeEl.selectionEnd); } else if (window.getSelection) { text = window.getSelection().toString(); } return text; } document.onmouseup = document.onkeyup = document.onselectionchange = function() { document.getElementById("sel").value = getSelectionText(); };
 Selection: <br> <textarea id="sel" rows="3" cols="50"></textarea> <p>Please select some text.</p> <input value="Some text in a text input"> <br> <input type="search" value="Some text in a search input"> <br> <input type="tel" value="4872349749823"> <br> <textarea>Some text in a textarea</textarea>

over 4 years ago · Santiago Trujillo Relatório

0

Obtenga texto resaltado de esta manera:

 window.getSelection().toString()

y por supuesto un trato especial para ej:

 document.selection.createRange().htmlText
over 4 years ago · Santiago Trujillo Relatório

0

Esta solución funciona si usa Chrome (no puede verificar otros navegadores) y si el texto se encuentra en el mismo elemento DOM:

 window.getSelection().anchorNode.textContent.substring( window.getSelection().extentOffset, window.getSelection().anchorOffset)
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda