He creado un documento HTML de "fragmentos" en el que tengo docenas de varios fragmentos con sus códigos en un área de texto de "solo lectura". Por lo tanto, los fragmentos pueden copiarse fácilmente en el portapapeles y pegarse en el contenido de una página web. No sé, cómo empaquetar todo el contenido de "onClick" en una sola función. Esto ahorraría una gran cantidad de código en todo el documento de "fragmentos", en lugar de usar este onClick="" en cada fragmento incluido. Este es mi código:
<h2><em>Snippet:</em> Intro page - bold text</h2> <form> <input title="One click transfers the code to the clipboard" type="button" value="Hilight & copy the code" onClick="this.form.code.select(),this.value = 'Hilighted code copied', document.execCommand('copy')"> <textarea name="code" readonly="readonly"> <!-- SNIPPET START --> *snippet code here* <!-- SNIPPET END --> </textarea> </form>Tu código debe usar ; en lugar de , pero si tiene más de un fragmento, debe delegar
document.getElementById("container").addEventListener("click", function(e) { let tgt = e.target.closest("input"); if (tgt && tgt.matches(".copy")) { const textarea = tgt.nextElementSibling; textarea.select(); tgt.value = 'Hilighted code copied'; document.execCommand('copy') } else tgt = e.target.closest("textarea"); if (tgt.matches("[name=code]")) tgt.select() }) <div id="container"> <h2><em>Snippet:</em> Intro page - bold text</h2> <input class="copy" title="One click transfers the code to the clipboard" type="button" value="Hilight & copy the code" /> <textarea name="code" readonly="readonly"> <!-- SNIPPET START --> *snippet code 1 here* <!-- SNIPPET END --> </textarea> <h2><em>Snippet:</em> Intro page - bold text</h2> <input class="copy" title="One click transfers the code to the clipboard" type="button" value="Hilight & copy the code" /> <textarea name="code" readonly="readonly"> <!-- SNIPPET START --> *snippet code 2 here* <!-- SNIPPET END --> </textarea> </div>Resuelto. El documento debe ser *.PHP. La variable se declarará, por ejemplo:
<?php $BTN = '<input class="copyBtn" title="Click to hilight & copy" type="button" value="Hilight & copy the code" />'; ?>El uso entonces es:
<?php echo $BTN;?>