Tengo problemas para averiguar cómo obtener la posición de intercalación en un contenedor DIV que contiene tags HTML.
Estoy usando esta función de JavaScript para hacer eso:
function getCaretPosition() { if (window.getSelection && window.getSelection().getRangeAt) { var range = window.getSelection().getRangeAt(0); var selectedObj = window.getSelection(); var rangeCount = 0; var childNodes = selectedObj.anchorNode.parentNode.childNodes; for (var i = 0; i < childNodes.length; i++) { if (childNodes[i] == selectedObj.anchorNode) { break; } if(childNodes[i].outerHTML) { rangeCount += childNodes[i].outerHTML.length; } else if(childNodes[i].nodeType == 3) { rangeCount += childNodes[i].textContent.length; } } return range.startOffset + rangeCount; } return -1; }
Sin embargo, encuentra una posición de intercalación del texto en mi contenedor DIV, cuando necesito encontrar la posición de intercalación, incluidas las tags HTML. Por ejemplo:
Text goes here along with some HTML tags.;
( Tenga en cuenta que las tags HTML son tags normales y no se muestran en la pantalla cuando la función devuelve la posición de cursor )
Si hago clic derecho entre H y TML, la función mencionada encontrará la posición de intercalación sin ningún problema. Pero estoy obteniendo los contenidos de la casilla DIV en formato HTML (incluidas todas las tags), y si quiero insertar algo en la posición de esa preocupación, algunos o muchos caracteres desaparecerán.
Revisé muchas publicaciones, pero todo lo que pude encontrar es
¿Alguien puede ayudar, por favor?
PD. Aquí está el código JQuery / Javascript que escribí para el botón de enlace:
$('#pageEditor').on('click', '.linkURL', function() { var cursorPosition; cursorPosition = getCaretPosition(); var contentID = $(this).parent().parent().attr('id'); var userSelected = getSelectionHtml(); var checkLink = userSelected.search(''); var anchorTag = 0; if(checkLink == -1) { var currentContents = $('#'+contentID+' .peCont').html(); var indexOfSelection = currentContents.indexOf(userSelected); var getPossibleAnchor = currentContents.slice(indexOfSelection, indexOfSelection+userSelected.length+6); anchorTag = getPossibleAnchor.search(''); } if(checkLink > 0 || anchorTag > 0) { //alert(checkLink); document.execCommand('unlink', false, false); } else { $('#'+contentID+' .peCont').append(''); $('#linkEntry').dialog({ buttons: { "Ok": function() { var attribute = $('#urlLink').val(); var newContentWithLink = ''; if(attribute != '') { if(userSelected != '') { var currentContent = $('#'+contentID+' .peCont').html(); var replacement = ''+userSelected+''; newContentWithLink = currentContent.replace(userSelected, replacement); } else { var currentTextContent = $('#'+contentID+' .peCont').html(); var userLink = 'https://stackoverflow.com/questions/11015313/get-caret-html-position-in-contenteditable-div/'+attribute+''; if(cursorPosition > 0) { var contentBegin = currentTextContent.slice(0,cursorPosition); var contentEnd = currentTextContent.slice(cursorPosition,currentTextContent.length); newContentWithLink = contentBegin+userLink+contentEnd; } else { newContentWithLink = attribute+currentTextContent; } } $('#'+contentID+' .peCont').empty(); $('#'+contentID+' .peCont').html(newContentWithLink); } $(this).dialog("close"); } }, closeOnEscape:true, modal:true, resizable:false, show: { effect: 'drop', direction: "up" }, hide: { effect: 'drop', direction: "down" }, width:460, closeText:'hide', close: function() { $(this).remove(); } }); $('#linkEntry').on('keypress', function(urlEnter) { if(urlEnter.which == 13) { var attribute = $('#urlLink').val(); var newContentWithLink = ''; if(userSelected != '') { var currentContent = $('#'+contentID+' .peCont').html(); var replacement = ''+userSelected+''; newContentWithLink = currentContent.replace(userSelected, replacement); } else { var currentTextContent = $('#'+contentID+' .peCont').html(); var userLink = 'https://stackoverflow.com/questions/11015313/get-caret-html-position-in-contenteditable-div/'+attribute+''; if(cursorPosition > 0) { var contentBegin = currentTextContent.slice(0,cursorPosition); var contentEnd = currentTextContent.slice(cursorPosition,currentTextContent.length); newContentWithLink = contentBegin+userLink+contentEnd; } else { newContentWithLink = attribute+currentTextContent; } } $('#'+contentID+' .peCont').empty(); $('#'+contentID+' .peCont').html(newContentWithLink); $(this).dialog("close"); } }); } });
Creé un violín simple para ti que hace lo que quieres.
Esto debería funcionar en las versiones recientes de Firefox, Chrome y Safari.
Es su tarea agregar soporte de Opera e IE si lo necesita.