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

231
Visualizações
¿Cómo copiar al portapapeles sin usar un btn? Para hacer clic que funciona en múltiples áreas de texto

Entonces, quiero crear un ClickToCopyToClipboard usando Javascript simple que cuando alguien haga clic en el área de texto, el contenido se copiará en el portapapeles. Eso funciona en múltiples áreas de texto. Pero todos los videos que vi de Youtube necesitan un botón para hacer clic.

Así que aquí está mi HTML:

 <div class="wrapper"> <textarea onclick="copytxt()">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque bibendum risus eros, eu mollis lorem consectetur eget.</textarea>

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque bibendum risus eros, eu mollis lorem consectetur eget.

Y aquí está mi JS:

 function copytxt(){ const textarea document.querySelector("textarea"); textarea.select(); document.execCommand("copy"); };
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Su JS está cerca, aunque tiene un error de sintaxis (falta = ). Aquí hay un ejemplo de trabajo con el estilo addEventListener adecuado, a diferencia del JS en línea.

 document.querySelector("textarea").addEventListener("click", function(){ this.select(); document.execCommand("copy"); });
 <textarea readonly>click me to copy my contents</textarea> <br><br> Then try pasting them in here: <input type="text"/>

about 4 years ago · Juan Pablo Isaza Relatório

0

intente agregar un detector de eventos al área de texto,

 <!DOCTYPE html> <html> <body> <p>Click anywhere in the textarea to copy the text from it. Try to paste the text (eg ctrl+v) afterwards in the input field given below, to see the effect.</p> <textarea type="text" value="Hello World" id="myInput"> hello world!!! </textarea> <input type="text" /> <script> /* Get the text field */ var copyText = document.getElementById("myInput"); copyText.addEventListener('click', () => { myFunction(); }) function myFunction() { /* Select the text field */ copyText.select(); copyText.setSelectionRange(0, 99999); /* For mobile devices */ /* Copy the text inside the text field */ navigator.clipboard.writeText(copyText.value); /* Alert the copied text */ alert("Copied the text: " + copyText.value); } </script> </body> </html>

EDITAR: si desea copiar desde múltiples áreas de texto de manera eficiente, puede probar esto

 <!DOCTYPE html> <html> <body> <p>Click anywhere in the textarea to copy the text from it. Try to paste the text (eg ctrl+v) afterwards in the input field given below, to see the effect.</p> <textarea type="text" value="first textarea" class="myInput"> first textarea </textarea> <textarea type="text" value="second textarea" class="myInput"> second textarea </textarea> <textarea type="text" value="third textarea" class="myInput"> third textarea </textarea> <textarea type="text" value="fourth textarea" class="myInput"> fourth textarea </textarea> <input type="text" /> <script> let x = document.querySelectorAll(".myInput"); for (let i = 0; i < x.length; i++) { x[i].addEventListener("click", function() { this.select(); document.execCommand("copy"); }); } </script> </body> </html>

Aquí, hice una matriz de todas las áreas de texto usando querySelectorAll y agregué un detector de eventos a cada área de texto de la matriz y la parte de copia está escrita en la función de devolución de llamada del detector de eventos. tenga en cuenta que todo aquí está escrito en javascript de vainilla simple y marque verde esta respuesta si fue útil.

about 4 years ago · Juan Pablo Isaza 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