1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2 <html xmlns="http://www.w3.org/1999/xhtml">
3 <head>
4 <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
5 <title>选择文本然后全选</title>
6 <script type="text/javascript" src="eventutil.js"></script>
7 </head>
8 <body>
9 <form action="#">
10 <input name="textbox1" type="text" value="test code" />
11 <!-- <textarea name="textbox1">test code</textarea> -->
12 </form>
13 <script type="text/javascript" src="test03.js"></script>
14 </body>
15 </html>
1 var textbox = document.forms[0].elements["textbox1"];
2
3 function selectText(textbox, startIndex, stopIndex) {
4 if (textbox.setSelectionRange) {
5 textbox.setSelectionRange(startIndex, stopIndex);
6 } else if (textbox.createTextRange) {
7 var range = textbox.createTextRange();
8 range.collapse(true);
9 range.moveStart("character", startIndex);
10 range.moveEnd("character", stopIndex - startIndex);
11 range.select();
12 }
13 textbox.focus();
14 }
15
16 textbox.value = "Hello world!";
17 console.log(textbox.value);
18
19 //选择所有文本
20 selectText(textbox, 0, textbox.value.length);
21
22 //选择前3个字符
23 selectText(textbox, 0, 3);
24
25 //选择第4到第6字符
26 selectText(textbox, 4, 7);