一、針對input、textareajavascript
//定位input、textarea function po_Last(obj) { obj.focus();//解決ff不獲取焦點沒法定位問題 if (window.getSelection) {//ie11 10 9 ff safari var max_Len=obj.value.length;//text字符數 obj.setSelectionRange(max_Len, max_Len); } else if (document.selection) {//ie10 9 8 7 6 5 var range = obj.createTextRange();//建立range range.collapse(false);//光標移至最後 range.select();//避免產生空格 } }
二、針對div(contenteditable="true")css
//定位div(contenteditable = "true") function po_Last_Div(obj) { if (window.getSelection) {//ie11 10 9 ff safari obj.focus(); //解決ff不獲取焦點沒法定位問題 var range = window.getSelection();//建立range range.selectAllChildren(obj);//range 選擇obj下全部子內容 range.collapseToEnd();//光標移至最後 } else if (document.selection) {//ie10 9 8 7 6 5 var range = document.selection.createRange();//建立選擇對象 //var range = document.body.createTextRange(); range.moveToElementText(obj);//range定位到obj range.collapse(false);//光標移至最後 range.select(); } }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>div contenteditable光標測試</title> <style type="text/css"> .div{ width:600px; height:200px; border:1px solid #CCC} </style> <script type="text/javascript" src="js/jquery-1.9.1.min.js"></script> <script type="text/javascript"> $(document).ready(function(e) { $('.aclick').click(function(){ $('.div').html("回覆[瀟sdfsdfssssssssssssssdfsdf瀟]:"); $('.div').focus(); po_Last_Div($('.div').get(0)); }) }); function po_Last_Div(obj) { if (window.getSelection) {//ie11 10 9 ff safari obj.focus(); //解決ff不獲取焦點沒法定位問題 var range = window.getSelection();//建立range range.selectAllChildren(obj);//range 選擇obj下全部子內容 range.collapseToEnd();//光標移至最後 } else if (document.selection) {//ie10 9 8 7 6 5 var range = document.selection.createRange();//建立選擇對象 //var range = document.body.createTextRange(); range.moveToElementText(obj);//range定位到obj range.collapse(false);//光標移至最後 range.select(); } } </script> </head> <body> <input type="text"> <div class="aclick">回覆瀟瀟</div> <div class="div" contenteditable="true"> </div> </body> </html>