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);
转载于:https://www.cnblogs.com/qzsonline/archive/2012/06/03/2532820.html
相关资源:46种常见的浏览器兼容性问题大汇总