可能重复:
在文本框的焦点上设置光标长度为 14
我有一个代码,它将焦点放在文本框中选择特定长度的子字符串。我想放置光标而不是选择整个字符串。代码如下
<script type="text/javascript">
window.onload = function() {
$("#message").keyup(function(e){
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-start);
selRange.select();
} else if( field.setSelectionRange ) {
field.setSelectionRange(start, end);
} else if( field.selectionStart ) {
field.selectionStart = start;
field.selectionEnd = end;
}
field.focus();
}}
</script>
HTML部分代码
<input type="text" name="message" id="message" value="" />