在contenteditable DIV中获取插入HTML的位置 [英] Get caret HTML position in contenteditable DIV

查看:155
本文介绍了在contenteditable DIV中获取插入HTML的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在使用这个JavaScript函数来做到这一点:

($)

 函数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)
{
打破;
}
if(childNodes [i] .outerHTML)
{
rangeCount + = childNodes [i] .outerHTML.length;
}
else if(childNodes [i] .nodeType == 3)
{
rangeCount + = childNodes [i] .textContent.length;
}
}
return range.startOffset + rangeCount;
}
返回-1;
}

然而,它会在我的DIV容器中找到文本的插入位置,我需要找到包含HTML标签的插入符号位置。
例如:

 < DIV class =peContcontenteditable =true>与< b>一些< i> HTML< / i>标记< / B个。< / DIV取代; 

请注意,HTML标记是正常标记,并且不会在屏幕上显示如果我在H和TML之间单击右键,前面提到的函数会发现插入符号的位置没有任何问题。但我以HTML格式(包括所有标签)获取DIV盒子的内容,如果我想在插入符的位置插入某些内容,我将会被几个或多个字符取消。



我经历了很多帖子,但是我能找到的只有< TEXTAREA>脱字号位置或功能类似于我发布的内容。到目前为止,我仍然无法找到解决方案,在HTML格式的文本中获取插入符号位置。



任何人都可以帮忙吗?

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

$($'$'$ $ $ $ $ $ $ $'$'$'$'$''''pageEditor')。 ,'.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>');
} $如果(checkLink> 0 || anchorTag> 0)
{
// alert(checkLink);
document.execCommand('unlink',false,假);


$ b {
$('#'+ contentID +'.peCont')。append('< div id =linkEntry><< ; label for =urlLink>请输入链接的URL:< label>< input type =textid =urlLink/>< / div>');
$('#linkEntry')。dialog({
buttons:{
Ok:function()
{
var attribute = $('#urlLink ').val();
var newContentWithLink =''; $ b $ 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);
}
});
}
});


解决方案

我创建了一个简单的小提琴为你做你想做的。



这应该在最近Firefox,Chrome和Safari版本。



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

I am having troubles figuring out how to get caret position in a DIV container that contains HTML tags.

I am using this JavaScript function to do that:

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

However, it finds a caret position of the text in my DIV container, when I need to find the caret position including HTML tags. For example:

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

(please note, that HTML tags are normal tags and are not displayed on the screen when the function is returning caret position)

If I click right between H and TML, the aforementioned function will find caret position without any problems. But I am getting the contents of DIV box in HTML format (including all tags), and if I want to insert something at that caret's position, I will be off by a few or many characters.

I went through many posts, but all I could find is either <TEXTAREA> caret postions, or functions similar to what I have posted. So far I still cannot find a solution to get a caret position in a text that has HTML formatting.

Can anyone help, please?

PS. Here's JQuery/Javascript code that I wrote for the link button:

$('#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");
            }
        });
    }
});

解决方案

I created a simple fiddle for you that does what you want.

This should work in recent versions of Firefox, Chrome and Safari.

It's your homework to add Opera and IE support if you need.

这篇关于在contenteditable DIV中获取插入HTML的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆