以编程方式在输入字段中选择部分文本 [英] Programmatically selecting partial text in an input field

查看:96
本文介绍了以编程方式在输入字段中选择部分文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何以编程方式在HTML 输入字段中选择特定范围的文本? (我不想选择整个字段,只是一个子集)

How can I programmatically select a specific range of text in an HTML input field? (I don't want to select the entire field, just a subset)

另外,如何确定当前选中的范围字段?

Also, how can I determine the currently selected range in a field?

推荐答案

以下是如何选择文本框的一部分(范围选择)并获取选定的文本:

Here's how to select a portion of a text box (range select) and get the selected text:

<!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>

演示

这篇关于以编程方式在输入字段中选择部分文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆