转自FR.richer的好文章:
各种浏览器下文本域中光标的定位关注用户体验,减少用户点击鼠标的次数,回复某人,点击回复之后,直接把光标定位到“回复XXX:”之后
测试页面如下:
01
?<!DOCTYPE html PUBLIC?
"-//W3C//DTD Xhtml 1.0 Transitional//EN"
?"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>?
02
?<html xmlns=
"http://www.w3.org/1999/xhtml"
>?
03
?<html>?
04
?
<head>?
05
?
<meta http-equiv=
"content-Type"
?content=
"text/html; charset=utf-8"
?/>?
06
?
<title> JS光标处理 </title>?
07
?
<meta name=
"Author"
?content=
"草依山@02web.com/hublog/"
>?
08
?
<meta name=
"Keywords"
?content=
" js cursor location "
>?
09
?
<meta name=
"Description"
?content=
" JS在文本框中的光标处理 "
>?
10
?
<script type=
"text/javascript"
>?
11
?
var
?$ =?
function
( _id ) {?
return
?typeof
?_id ===?
'string'
?? document.getElementById( _id ) :?
null
?};?
12
?
13
?
doReply =?
function
()?
14
?
{?
15
?
var
?replyBox = $(?
'reply'
?);?
16
?
17
?
replyBox.value +=?
"回复XXX:"
;?
18
?
19
?
replyBox.focus();?
20
?
}?
21
?
</script>?
22
?
</head>?
23
?
24
?
<body>?
25
?
<a href=
"#"
?onclick=
"doReply()"
>我是小星哈哈</a>?
26
?
<br/>?
27
?
<textarea name=
"reply"
?id=
"reply"
?rows=
"6"
?cols=
"20"
></textarea>?
28
?
<br/>?
29
?
<a href=
"http://www.google.com"
?title=
"搜索"
>小星星</a>?
30
?
</body>?
31
?</html>
恩, 这是第一个页面,点击我是小星,文本域里会出现回复XXX字样,在火狐下光标会默认聚集到最后,在IE下如果你在点我是小星之前的光标是在文本域中的,那 么你很幸运,光标还是在最后,但是在你点我是小星之前光标不是在文本域,这时光标就会定位到最前面,看到现象了,那我们就知道怎么办了,在IE下每次点击 填文字之前先focus一下就行了,有了下面的改进的doReply函数
01
?doReply =?
function
()?
02
?{?
03
?
04
?
var
?replyBox = $(?
'reply'
?);?
05
?
06
?
replyBox.focus();?
07
?
08
?
replyBox.value +=?
"回复XXX:"
;?
09
?
10
?
replyBox.focus();?
11
?}
这个很好的解决了问题,可是如果某天要求光标定位到最开始呢,IE下好办,先让文本域失去焦点,再填值,再去focus就可以了,试验发现不行,就算通过 了可是火狐怎么办呢?并且上面的方法也始终是一个不是办法的办法,有没有科学一点的呢?为了避免将来更变态的定位需求,那就搞一下光标定位呗,定位在富文 本编辑器里很常用,不过那里跟这里又好像不太一样,一般的富文本编辑器,如tinyMce和ckEditor都是用iframe作为文本编辑的区域的,这 里只是一个文本域,废话不多说,研究一下。
IE支持的textRange可以方便的实现这个,关于IE的这个对象详细的可以看这里,火狐支持setSelectionRange(),详见这里,注意文档的后面一句,把两个值设为相同就可以把光标定位在指定的位置并且不会有选中出现,OK,建一个setCursorPos函数如下
01
?var
?setCursorPos =?
function
( el, pos )?
02
?{?
03
?
if
( el.createTextRange )?
04
?
{?
05
?
var
?rng = el.createTextRange();?
//新建textRange对象?
06
?
rng.moveStart(?
'character'
, pos );?
//更改rng对象的开始位置?
07
?
rng.collapse(?
true
?);?
//光标移动到范围结尾?
08
?
rng.select();
//选中?
09
?
el.focus();?
10
?
}
else
?if
( el.setSelectionRange )?
11
?
{?
12
?
el.focus();?
//先聚集?
13
?
el.setSelectionRange( pos , pos );?
//设光标?
14
?
}?
15
?}
恩,有了这些,我们就可以把页面重新弄一下了