1

在使文本 DIV 可编辑时,我使用 setEndOfContenteditable 函数将光标置于文本末尾。

//Insert cursor at end of contentEditable element
function setEndOfContenteditable(contentEditableElement)
{
    var range,selection;
    if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
    {
        range = document.createRange();//Create a range (a range is a like the selection but invisible)
        range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
        range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
        selection = window.getSelection();//get the selection object (allows you to change selection)
        selection.removeAllRanges();//remove any selections already made
        selection.addRange(range);//make the range you have just created the visible selection
    }
    else if(document.selection)//IE 8 and lower
    { 
        range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
        range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
        range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
        range.select();//Select the range (make it the visible selection
    }
}

当我以前只有一个 div 和其中的文本时,这将完美地工作:

setEndOfContenteditable(curObj);

curObj 是其中包含文本的 DIV。

现在我已经切换到一个设计,我仍然有 curObj -div 但只是作为一个框架,包含实际文本的 DIV 位于其中。通常我这样做是为了达到(选择)我的 jQuery 代码中的内部 div

var curObj = window.curObj;
var inner = '#' + $(curObj).attr("id") + ' .object_inner';
$(inner).doAllMyStuff;

但是,这不适用于这个特定的 setEndOfContenteditable 函数,我得到的错误是

Uncaught Error: NotFoundError: DOM Exception 8 

以及 setEndOfContenteditable 函数第 7 行的错误点:

range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
4

1 回答 1

0

啊,我试图将一个 jQuery 选择器传递给一个普通的 javascript 函数(它需要一个原始 DOM 元素)。这是一种解决方案,它获取原始 DOM 元素:

var spec = $(curObj).find('.object_inner');
setEndOfContenteditable(spec[0]);

特别感谢这个人: How to get a DOM Element from a JQuery Selector

于 2013-10-02T13:11:55.507 回答