当使 text-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
最佳答案
啊,我试图将 jQuery 选择器传递给普通的 javascript 函数(需要原始 DOM 元素)。这是一种解决方案,它获取原始 DOM 元素:
var spec = $(curObj).find('.object_inner');
setEndOfContenteditable(spec[0]);
关于javascript - 无法使用javascript到达DIV的节点内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19137570/