【问题标题】:Input not scrolling to the far right like it should输入没有像应有的那样滚动到最右边
【发布时间】:2016-01-31 14:35:58
【问题描述】:

我有一个输入字段,我在光标位置附加数据。

之后,我将 selectionStart 设置为字段的末尾。

但是,每当我向输入添加内容(通过单击按钮)时,我只会看到它的左侧部分(直到它到达右边缘)。一切都在那里(我可以用鼠标和滚动选择它),但它不会自动显示右边缘。

我该怎么做? 我想在输入中添加一些内容并直接跳到字符串的末尾。

  // add 2 digit number
  $('button#2digit').on('click', function add2digit() {
    addNumberToInput(10, 99);
  });

  function addNumberToInput(min, max) {
    var problemInput = $('input#testProblem');
    if (lastCharIsOperation() || problemInput.val().trim() < 1) {  // if last char is an operation or first in string, just append the number
      addAtCursor(randomNonPrime(min, max));
    } else {
      addAtCursor('+' + randomNonPrime(min, max));
    }
  }



  function addAtCursor(toAdd) {
    var problemInput = $('input#testProblem');

    var oldText = problemInput.val();
    var cursor = problemInput[0].selectionStart;

    var pre = oldText.substring(0,cursor);
    var post = oldText.substring(cursor, oldText.length);

    //insert at cursor
    problemInput.val(pre + toAdd + post);

    //put cursor to end
    problemInput[0].selectionStart = problemInput.val().length;
  }

(它甚至会在模糊时跳回左侧,我无法使用 windows 截图工具制作图片,因为我必须先点击它)

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:

    来自Set mouse focus and move cursor to end of input using jQuery

    var problemInput = $('input#testProblem');
    problemInput.focus();
    var t=problemInput.val();
    problemInput.val('');
    problemInput.val(t);
    

    这里是完整解决方案的开始:https://jsfiddle.net/michaelgentry/vwm159pt/

    【讨论】:

    • 也跳回模糊:/有没有办法解决这个问题?
    • 查看编辑中的小提琴,这应该是你想要的。虽然 CSS 还不完美,但您必须这样做。
    • wheeewww 这太笨重了.. 我希望这种微不足道的事情会有更简单的方法。到目前为止,谢谢,我可以处理这个:)
    【解决方案2】:

    这仍然会导致滚动在模糊时跳回左侧,但会按照您的要求进行:

     var elem = document.getElementById('myInput');
     elem.focus();
     elem.scrollLeft = elem.scrollWidth;
    

    【讨论】:

      猜你喜欢
      • 2020-10-10
      • 1970-01-01
      • 1970-01-01
      • 2021-06-25
      • 1970-01-01
      • 1970-01-01
      • 2021-11-13
      • 2021-10-31
      • 2012-12-20
      相关资源
      最近更新 更多