设置鼠标焦点,并使用jQuery将光标移动到输入结束 [英] Set mouse focus and move cursor to end of input using jQuery

查看:121
本文介绍了设置鼠标焦点,并使用jQuery将光标移动到输入结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题以几种不同的格式提出,但我无法得到任何答案在我的情况下工作。

This question has been asked in a few different formats but I can't get any of the answers to work in my scenario.

我使用jQuery来实现用户点击向上/向下箭头时的命令历史。当命中向上箭头时,我用上一个命令替换输入值,并在输入字段上设置焦点,但希望光标始终位于输入字符串的末尾。

I am using jQuery to implement command history when user hits up/down arrows. When up arrow is hit, I replace the input value with previous command and set focus on the input field, but want the cursor always to be positioned at the end of the input string.

我的代码,如下:

$(document).keydown(function(e) {
  var key   = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
  var input = self.shell.find('input.current:last');

  switch(key) {
    case 38: // up
      lastQuery = self.queries[self.historyCounter-1];
      self.historyCounter--;
      input.val(lastQuery).focus();
// and it continues on from there

我强制光标放在焦点后的'input'的末尾?

How can I force the cursor to be placed at the end of 'input' after focus?

推荐答案

看起来像在聚焦后清除值然后重置工作。

Looks like clearing the value after focusing and then resetting works.

input.focus();
var tmpStr = input.val();
input.val('');
input.val(tmpStr);

这篇关于设置鼠标焦点,并使用jQuery将光标移动到输入结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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