关于光标操作,终于搞定了FF下DIV的光标控制

什么都不说了,直接上代码

function getCaretPos(element) { var CaretPos = 0; // IE Support if (document.selection) { element.focus (); //将焦点至于element,并且光标位置不会发生改变 var Sel = document.selection.createRange(); //document.selection可以获得当前所选区域,而createRange则返回对应的TextRange对象,该对象不包含任何文本 Sel.moveStart ('character', -element.innerText.length); //将光标往后退文本的长度 var text = Sel.text;//Range对象所包括的文本,由于是整个文档的textRange所以,前面几个字符有可能不是element中的,所以要做最长匹配 for (var i = 0; i < element[element.tagName=='DIV'?'innerText':'value'].length; i++) { if (element[element.tagName=='DIV'?'innerText':'value'].substring(0, i + 1) == text.substring(text.length - i - 1, text.length)) { CaretPos = i + 1; } } var lines = element[element.tagName=='DIV'?'innerText':'value'].substring(0, CaretPos).split('/n').length - 1; CaretPos -= lines; //range对象中换行一个字符,当时在String中换行是/n两个字符 } // Firefox support only for textarea and input else if (element.selectionStart || element.selectionStart == '0') CaretPos = element.selectionStart; // Firefox support only for div else if (window.getSelection) { var sel = window.getSelection(); var rng = sel.getRangeAt(0).cloneRange(); rng.setStart(element, 0); CaretPos = rng.toString().length; } alert(CaretPos); } function setCaretPos(/*DomNode*/ element, /*Number*/ location){ if(element.setSelectionRange) { element.focus(); element.setSelectionRange(location,location); } else if (document.body.createTextRange) { var range = document.body.createTextRange(); range.moveToElementText(element); range.collapse(true); range.move('character', location); range.select(); } else if (window.getSelection) { var nodes = []; var getTextNode = function(node) { for (var i = 0; i < node.childNodes.length; i++) { if (node.childNodes[i].nodeType == 3) { nodes.push(node.childNodes[i]); } else { getTextNode(node.childNodes[i]); } } } getTextNode(element); var length = 0; for (var i = 0; i < nodes.length; i++) { length += nodes[i].textContent.length; if (length > location) { length -= nodes[i].textContent.length; break; } } var sel = window.getSelection(); sel.collapse(nodes[i], location - length); element.focus(); } } 

你可能感兴趣的:(function,String,input,div,character,firefox)