文本框中的字符串截取方法

 

1 function getSelectedText(textbox) {
2 if (document.selection) {
3 return document.selection.createRange().text;
4 } else {
5 return textbox.value.substring(textbox.selectionStart,textbox.selectionEnd);
6 }
7 }

IE9之前不提供selectionStart,selectionEnd属性

下面是根据起始位置和结束位置选取字符串:

1 function selectText(textbox, startIndex, stopIndex) {
2 if (textbox.setSelectionRange) {
3 textbox.setSelectionRange(startIndex, stopIndex);
4 } else if (textbox.createTextRange) {
5 var range = textbox.createTextRange();
6 range.collapse(true);
7 range.moveStart("character", startIndex);
8 range.moveEnd("character", stopIndex - startIndex);
9 range.select();
10 }
11 textbox.focus();
12 }

posted @ 2011-05-15 15:09  HelloWorld.Michael  阅读(510)  评论(0)    收藏  举报