Necesito poder representar algunas etiquetas HTML dentro de un área de texto (es decir, <strong>, <i>, <u>, <a>), pero las áreas de texto solo interpretan su contenido como texto. ¿Hay una manera fácil de hacerlo sin depender de bibliotecas/complementos externos (estoy usando jQuery)? Si no, ¿conoce algún complemento de jQuery que pueda usar para hacer esto?
Esto no es posible de hacer con un área de textarea . Está buscando un div editable de contenido , que se hace muy fácilmente:
<div contenteditable="true"></div> div.editable { width: 300px; height: 200px; border: 1px solid #ccc; padding: 5px; } strong { font-weight: bold; } <div contenteditable="true">This is the first line.<br> See, how the text fits here, also if<br>there is a <strong>linebreak</strong> at the end? <br>It works nicely. <br> <br><span style="color: lightgreen">Great</span>. </div>Con un div editable, puede usar el método document.execCommand ( más detalles ) para proporcionar fácilmente el soporte para las etiquetas que especificó y para alguna otra funcionalidad...
#text { width: 500px; min-height: 100px; border: 2px solid; } <div id="text" contenteditable="true"></div> <button onclick="document.execCommand('bold');">toggle bold</button> <button onclick="document.execCommand('italic');">toggle italic</button> <button onclick="document.execCommand('underline');">toggle underline</button>Ya que solo dijiste render, sí puedes. Podrías hacer algo similar a esto:
function render(){ var inp = document.getElementById("box"); var data = ` <svg xmlns="http://www.w3.org/2000/svg" width="${inp.offsetWidth}" height="${inp.offsetHeight}"> <foreignObject width="100%" height="100%"> <div xmlns="http://www.w3.org/1999/xhtml" style="font-family:monospace;font-style: normal; font-variant: normal; font-size:13.3px;padding:2px;;"> ${inp.value} <i style="color:red">cant touch this</i> </div> </foreignObject> </svg>`; var blob = new Blob( [data], {type:'image/svg+xml'} ); var url=URL.createObjectURL(blob); inp.style.backgroundImage="url("+URL.createObjectURL(blob)+")"; } onload=function(){ render(); ro = new ResizeObserver(render); ro.observe(document.getElementById("box")); } #box{ color:transparent; caret-color: black; font-style: normal;/*must be same as in the svg for caret to align*/ font-variant: normal; font-size:13.3px; padding:2px; font-family:monospace; } <textarea id="box" oninput="render()">you can edit me!</textarea>textarea html! Además del parpadeo al cambiar el tamaño, la incapacidad de usar clases directamente y tener que asegurarse de que el div en el svg tenga el mismo formato que el área de textarea para que el símbolo de intercalación se alinee correctamente, ¡funciona!