1. 程式人生 > >js 光標位置處理

js 光標位置處理

() selection text 位置信息 blog use select pos users

  /**
* 獲取選中文字
* 返回selection,toString可拿到結果,selection含有起始光標位置信息等
**/
function getSelectText() { var text, userSelection = window.getSelection()||document.selection.createRange();// not IE || ie if (!(text = userSelection.text)) text = userSelection; return text; }
/**
* 獲取光標位置
* 對 input、textarea有效,對contenteditable:true方式不生效
**/
function getCursortPosition (textDom) { var cursorPos = 0; if (document.selection) { // IE Support textDom.focus (); var selectRange = document.selection.createRange(); selectRange.moveStart (
‘character‘, -textDom.value.length); cursorPos = selectRange.text.length; }else if (textDom.selectionStart || textDom.selectionStart == ‘0‘) { // 非 IE cursorPos = textDom.selectionStart; } return cursorPos; } /**
* 設置光標位置
* 有效對象同光標獲取
**/
function setCaretPosition(textDom, pos){
if(textDom.setSelectionRange) { // IE Support textDom.focus(); textDom.setSelectionRange(pos, pos); }else if (textDom.createTextRange) { // 非 IE var range = textDom.createTextRange(); range.collapse(true); range.moveEnd(‘character‘, pos); range.moveStart(‘character‘, pos); range.select(); } }

js 光標位置處理