将插入符移动到文本输入字段的末尾并使结尾可见

时间:2010-04-22 15:09:36

标签: javascript javascript-events input textinput

我疯了。我有一个自动提示框,用户可以在其中选择建议。在下一个建议选择中,文本输入框的值超出其大小。我可以将克拉移动到输入字段crossbrowser的末尾,没问题。但在Chrome和Safari上我最终无法看到克拉。文本的末尾不可见。

有没有办法将克拉移动到文本输入字段的末尾并且字段的末尾可见,这样用户就不会对输入克拉的位置感到困惑?

到目前为止我得到了什么:

<html>
<head><title>Field update test</title></head>

<body>
<form action="#" method="POST" name="testform">

<p>After a field is updated the carat should be at the end of the text field AND the end of the text should be visible</p>

<input type="text" name="testbox" value="" size="40">

<p><a href="javascript:void(0);" onclick="add_more_text();">add more text</a></p>

</form>

<script type="text/javascript">
<!--
var count = 0;

function add_more_text() {
   var textfield = document.testform.elements['testbox'];

   textfield.focus();

   if (count == 0) textfield.value = ''; // clear old

   count++;
   textfield.value = textfield.value + (textfield.value.length ? ', ' : '') + count + ": This is some sample text";

   // move to the carat to the end of the field
   if (textfield.setSelectionRange) {
      textfield.setSelectionRange(textfield.value.length, textfield.value.length);
   } else if (textfield.createTextRange) {
      var range = textfield.createTextRange();
      range.collapse(true);
      range.moveEnd('character', textfield.value.length);
      range.moveStart('character', textfield.value.length);
      range.select();
   }

   // force carat visibility for some browsers
   if (document.createEvent) {
      // Trigger a space keypress.
      var e = document.createEvent('KeyboardEvent');
      if (typeof(e.initKeyEvent) != 'undefined') {
         e.initKeyEvent('keypress', true, true, null, false, false, false, false, 0, 32);
      } else {
         e.initKeyboardEvent('keypress', true, true, null, false, false, false, false, 0, 32);
      }
      textfield.dispatchEvent(e);

      // Trigger a backspace keypress.
      e = document.createEvent('KeyboardEvent');
      if (typeof(e.initKeyEvent) != 'undefined') {
         e.initKeyEvent('keypress', true, true, null, false, false, false, false, 8, 0);
      } else {
         e.initKeyboardEvent('keypress', true, true, null, false, false, false, false, 8, 0);
      }
      textfield.dispatchEvent(e);
   }
}
// -->
</script>

</body>
</html>

由于

1 个答案:

答案 0 :(得分:1)

我想出了一个解决方案。 Webkit(Safari和Chrome)需要穿上裤子来正确执行键盘事件。在退格之前添加blur()然后focus():

  textfield.blur(); // Webkit wake-up hack
  textfield.focus();
  textfield.dispatchEvent(e);

感谢。适用于Mac和Windows上的Safari,Chrome,FF,IE。