在contenteditable DIV中获取插入符号HTML位置

时间:2012-06-13 12:55:43

标签: javascript html contenteditable caret

我在找出如何在包含HTML标记的DIV容器中获取插入位置时遇到了麻烦。

我正在使用此JavaScript函数来执行此操作:

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;
}

但是,当我需要找到包含HTML标签的插入位置时,它会在我的DIV容器中找到文本的插入位置。 例如:

<DIV class="peCont" contenteditable="true">Text goes here along with <b>some <i>HTML</i> tags</b>.</DIV>;

请注意,HTML标签是普通标签,当功能返回插入位置时,屏幕上不会显示

如果我在H和TML之间单击,上述功能将找到插入位置而没有任何问题。但是我正在以HTML格式(包括所有标签)获取DIV框的内容,如果我想在该插入符号的位置插入一些内容,我会被一些或多个字符所取代。

我经历了很多帖子,但我能找到的只是&lt; TEXTAREA&gt;插入位置,或类似于我发布的功能。到目前为止,我仍然找不到在具有HTML格式的文本中获取插入位置的解决方案。

有人可以帮忙吗?

PS。这是我为链接按钮编写的JQuery / Javascript代码:

$('#pageEditor').on('click', '.linkURL', function()
{
    var cursorPosition;
    cursorPosition = getCaretPosition();
    var contentID = $(this).parent().parent().attr('id');
    var userSelected = getSelectionHtml();
    var checkLink = userSelected.search('</a>');
    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('</a>');
    }

    if(checkLink > 0 || anchorTag > 0)
    {
        //alert(checkLink);
        document.execCommand('unlink', false, false);

    }
    else
    {
        $('#'+contentID+' .peCont').append('<div id="linkEntry"><label for="urlLink">Please enter URL for the link:<label><input type="text" id="urlLink" /></div>');
        $('#linkEntry').dialog({
             buttons: { 
                "Ok": function() 
                {
                    var attribute = $('#urlLink').val();
                    var newContentWithLink = '';
                    if(attribute != '')
                    {
                        if(userSelected != '')
                        {
                            var currentContent = $('#'+contentID+' .peCont').html();
                            var replacement = '<a href="'+attribute+'">'+userSelected+'</a>';
                            newContentWithLink = currentContent.replace(userSelected, replacement);
                        }
                        else
                        {
                            var currentTextContent = $('#'+contentID+' .peCont').html();
                            var userLink = '<a href="'+attribute+'">'+attribute+'</a>';
                            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 = '<a href="'+attribute+'">'+userSelected+'</a>';
                    newContentWithLink = currentContent.replace(userSelected, replacement);
                }
                else
                {
                    var currentTextContent = $('#'+contentID+' .peCont').html();
                    var userLink = '<a href="'+attribute+'">'+attribute+'</a>';
                    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");
            }
        });
    }
});

1 个答案:

答案 0 :(得分:-1)

我为你创造了一个简单的fiddle,可以做你想要的。

这应该适用于最新版本的Firefox,Chrome和Safari。

如果需要,可以添加Opera和IE支持。

相关问题