首页 > 代码库 > JS 对文本框指定焦点差入值

JS 对文本框指定焦点差入值

参考文章:http://www.111cn.net/wy/js-ajax/52270.htm


这种方法可行。

通过上面的我们就可以将DIV中的光标移动到最后面了

一个完整的实例

 代码如下复制代码

<button type=”button” onclick=”document.getElementById(‘test’).focus(); insertHtmlAtCaret(‘<b>INSERTED</b>’);”>插入字符</button>
<div contentEditable=”true” style=”height:50px; border:2px solid red;” id=”test”>&nbsp;</div>

 

function insertHtmlAtCaret(html) {
var sel, range;
if (window.getSelection) {
// IE9 and non-IE
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();

// Range.createContextualFragment() would be useful here but is
// non-standard and not supported in all browsers (IE9, for one)
var el = document.createElement(“div”);
el.innerHTML = html;
var frag = document.createDocumentFragment(), node, lastNode;
while ( (node = el.firstChild) ) {
lastNode = frag.appendChild(node);
}
range.insertNode(frag);

// Preserve the selection
if (lastNode) {
range = range.cloneRange();
range.setStartAfter(lastNode);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
}
} else if (document.selection && document.selection.type != “Control”) {
// IE < 9
document.selection.createRange().pasteHTML(html);
}
}



本文出自 “JianBo” 博客,转载请与作者联系!

JS 对文本框指定焦点差入值