如何以编程方式在HTML input字段中选择特定范围的文本?(我不想选择 整个 字段,而只是选择一个子集)
input
另外,如何确定字段中当前选择的范围?
以下是选择文本框的一部分(范围选择)并获取所选文本的方法:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title> Test </title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript"> window.onload = function() { var message = document.getElementById('message'); // Select a portion of text createSelection(message, 0, 5); // get the selected portion of text var selectedText = message.value.substring(message.selectionStart, message.selectionEnd); alert(selectedText); }; function createSelection(field, start, end) { if( field.createTextRange ) { var selRange = field.createTextRange(); selRange.collapse(true); selRange.moveStart('character', start); selRange.moveEnd('character', end); selRange.select(); field.focus(); } else if( field.setSelectionRange ) { field.focus(); field.setSelectionRange(start, end); } else if( typeof field.selectionStart != 'undefined' ) { field.selectionStart = start; field.selectionEnd = end; field.focus(); } } </script> </head> <body> <input type="text" name="message" id="message" value="Hello World" /> </body> </html>