Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

78
Views
¿Cómo insertar una etiqueta HTML en la misma etiqueta <div> en un solo evento de pulsación de tecla? (en JQuery o Javascript)

Quiero insertar una etiqueta HTML en un evento de pulsación de tecla. Soy nuevo en JQuery y Javascript, y también busqué esta cosa, pero no obtuve respuesta para esta cosa

Conozco los métodos append y selectionStart pero quiero insertar en la posición del cursor de texto

Por ejemplo, si escribo la letra 'a', debería enviar <img src='a.png'> al div, en la posición del cursor

 $("#textcontent").contentEditable = "true"; $(document).ready(function(){ $("#textcontent").keydown(function(event){ $("#textcontent").append("<img src='" + event.key +".png'>");

Pero, esto (el código adjunto JS en la parte superior) no es lo que quiero, pero quiero insertar una etiqueta HTML en la posición actual del cursor de texto

Mi HTML:

 <div class="textcontent" contenteditable="true"> <img src='h.png'> ... // more image tags goes here </div>

¿Puede alguien por favor dar algunas respuestas para este problema?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Mira esto:

imagen 1

imagen 2


 $("#textcontent").keydown(function(event) { if (event.key === "Backspace") return; // allow backspace to clear image if (!/^[a-zA-Z0-9]{1,1}$/.test(event.key)) return false; // just allow az and 0-9 const position = document.getSelection().anchorOffset; // get position const newElement = $(`<img alt="${event.key}" src="https://eu.ui-avatars.com/api/?name=${event.key}">`); // create new element const element = [...$("#textcontent img")][position]; // get previous element on index "position" if (element) textcontent.insertBefore(newElement.get(0), element); // prepend element else $("#textcontent").append(newElement); // append element /* OPTIONAL! place caret at the end */ textcontent.focus(); const range = document.createRange(); range.selectNodeContents(textcontent); range.collapse(false); const selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(range); /**/ return false; // cancel event to avoid text inside div });
 #textcontent { border: 2px solid gray; padding: 10px; border-radius: 10px; } img { margin-left: 7px; width: 30px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="textcontent" contenteditable="true"></div>

about 4 years ago · Juan Pablo Isaza Report

0

Hice algunos cambios en el código de @jns y esto es lo que se me ocurrió...

Se agregó la función para usar caracteres en minúsculas, espacio y también para algunos otros símbolos...

¡Gracias @jns!

 $("#textcontent").keydown(function(event) { if ((event.key === "Backspace")||(event.ctrlKey)||(event.altKey)||(event.keyCode == 46)||(event.which>=33 && event.which <=40)) return; // Allow other keys to do their normal functions (not for Enter key) if (!/^[a-zA-Z0-9\/`~=\[\]'\\; ]$/.test(event.key)) return false; // Just allows AZ, az, 0-9, and also characters like `~=[];'\/ var letter_name = event.key; var uppercase = "false"; if (event.key === ' ' || event.key === 'Spacebar') // To add spacebar input feature ('Spacebar' for IE9 and Firefox < 37) letter_name = ''; else letter_name = event.key; if (/^[AZ]$/.test(letter_name)) // To chech whether its an uppercase letter uppercase = "true"; else uppercase = "false"; const position = document.getSelection().anchorOffset; // get position const newElement = $(`<img alt="${letter_name}" src="https://eu.ui-avatars.com/api/?uppercase=${uppercase}&name=${letter_name}">`); // create new element const element = [...$("#textcontent img")][position]; // get previous element on index "position" if (element) textcontent.insertBefore(newElement.get(0), element); // prepend element else $("#textcontent").append(newElement); // append element /* OPTIONAL! place caret at the end */ textcontent.focus(); const range = document.createRange(); range.selectNodeContents(textcontent); range.collapse(false); const selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(range); /**/ return false; // cancel event to avoid text inside div });
 #textcontent { border: 2px solid gray; padding: 10px; border-radius: 10px; } img { margin-left: 7px; width: 30px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="textcontent" contenteditable="true"></div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!