js-处理div设置的编辑框处理焦点定位追加内容
具体实现方法如下:
首先要让DIV启用编辑模式
<div contenteditable=true id="divTest"></div>
通过设定contenteditable=true开启div的编辑模式.这样DIV就可以跟文本框一样输入内容了。
不扯话题了。下面说怎么获取或设置光标位置.
2个步骤:
① 获取DIV中的光标位置
② 改变光标位置
var cursor = 0; // 光标位置 document.onselectionchange = function () { var range = document.selection.createRange(); var srcele = range.parentElement();//获取到当前元素 var copy = document.body.createTextRange(); copy.moveToElementText(srcele); for (cursor = 0; copy.compareEndPoints("StartToStart", range) < 0; cursor++) { copy.moveStart("character", 1);//改变光标位置,实际上我们是在记录cursor的数量. } }
给document绑定光标变化事件。用来记录光标位置.
这样就可以拿到DIV的光标位置了.
function moveEnd(obj) { lyTXT1.focus(); var r = document.selection.createRange(); //因为这里死从当前光标开始移动的(好像文本框的是从0算起.)所以我们需要拿到当前光标位置,然后就可以计算出要移动多少位了,这样就可以把光标移动到想要的位置了 r.moveStart('character', lyTXT1.innerText.length - cursor); r.collapse(true); r.select(); }
给document绑定光标变化事件。用来记录光标位置.
这样就可以拿到DIV的光标位置了.
function moveEnd(obj) { lyTXT1.focus(); var r = document.selection.createRange(); //因为这里死从当前光标开始移动的(好像文本框的是从0算起.)所以我们需要拿到当前光标位置,然后就可以计算出要移动多少位了,这样就可以把光标移动到想要的位置了 r.moveStart('character', lyTXT1.innerText.length - cursor); r.collapse(true); r.select(); }
通过上面的我们就可以将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"> </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);
}
}
知识只有共享才能传播,才能推崇出新的知识,才能学到更多,这里写的每一篇文字/博客,基本都是从网上查询了一下资料然后记录下来,也有些是原滋原味搬了过来,也有时加了一些自己的想法

浙公网安备 33010602011771号