Quiero usar execCommand('formatblock')
para seleccionar una línea con la etiqueta
o con una clase o id específico o cualquier estilo CSS en mi contentEditable
document.execCommand('formatblock', false, 'p'>;
¿Cómo puedo agregar una clase o id o CSS en este código?
Si desea agregar id o clase para CSS en contenido editable div, entonces usará el siguiente código —
.oder2 { padding-left: 3em; }
Tengo la solución.
Javascript:
function line(){ window.execCommand('formatblock', false, 'p'); selectedElement = window.getSelection().focusNode.parentNode; selectedElement.style.marginBottom = '100px'; }
HTML
Esto es perfecto para mi. Pero no puedo hacer jsfiddle en este momento. Este es el trabajo para una línea fina pero no para varias líneas.
Pruebe este código: http://jsfiddle.net/lotusgodkk/GCu2D/57/
Javascript:
$(document).ready(function () { $('div').click(function () { var sel = window.getSelection(); var range = document.createRange(); el = document.getElementById('one'); //Get the element range.selectNodeContents(el); sel.removeAllRanges(); sel.addRange(range); document.execCommand('formatblock', false, null); //execute command. document.execCommand('bold', false, null); //execute command. }); });
HTML
Sample text
Sample text 2
Hay muchas formas de hacerlo. Simplemente use execCommand ‘insertHTML’ en su lugar para reemplazar el texto seleccionado con el código ajustado. Me gusta esto:
selection = window.getSelection().toString(); wrappedselection = '' + selection + ''; document.execCommand('insertHTML', false, wrappedselection);
Esto eliminará las líneas de corte, tags como ,
y otras intext-html-formatting – para mantenerlas así de necesarias (thx para publicar ):
selection = window.getSelection().getRangeAt(0).cloneContents(); span = document.createElement('span'); span.appendChild(selection); wrappedselection = ''+span.innerHTML+''; document.execCommand('insertHTML', false, wrappedselection);
Este insertHTML no funciona con IE. Consulte la documentación https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand
Tuve el mismo problema. Terminé usando jQuery.
document.execCommand(optionCommand, false, null); let snippets = $('.js-editor-content-snippet'); let lists = snippets.find('ul, ol'); lists.css({ margin: '0', padding: '0 0 0 20px' }); lists.find('li').css({ margin: '0 0 12px' });
También hay esta gran biblioteca que podría ser útil: https://github.com/timdown/rangy/wiki/Class-Applier-Module
rangy.createClassApplier(String theClass[, Object options[, Array tagNames]])