简体   繁体   English

当内容大于输入字段(在Chrome中)时,如何将光标/尖号移动到输入字段中的最后一个字符?

[英]How to move cursor/caret to last character in input field when content is larger than input field (in Chrome)?

What's the current situtation: 当前的情况是什么:

I've successfully get this working (don't ask, stupid feature request) in all browsers: 我已经在所有浏览器中成功完成了此工作(不要问,愚蠢的功能请求):

  1. User clicks into input field (that has value content) 用户单击输入字段(具有值内容)
  2. The cursor jumps right after the last character of the input's content 光标跳到输入内容的最后一个字符之后

See a working JSfiddle demo here (there are different possibilites to implement this btw). 在此处查看有效的JSfiddle演示 (实现此操作有不同的可能性)。

HTML HTML

<input id="test" value="Something" />

JS JS

function moveCaretToEnd(el) {
    if (typeof el.selectionStart == "number") {
        el.selectionStart = el.selectionEnd = el.value.length;
    } else if (typeof el.createTextRange != "undefined") {
        el.focus();
        var range = el.createTextRange();
        range.collapse(false);
        range.select();
    }
}

var textarea = document.getElementById("test");
textarea.onfocus = function() {
    moveCaretToEnd(this);

    // Work around Chrome's little problem
    textarea.onmouseup = function() {
    // Prevent further mouseup intervention
    moveCaretToEnd(this);
    textarea.onmouseup = null;
    return false;
    };
};    

What I want to reach and what's blocking: 我想达到的目标和阻碍因素:

This does not work anymore in Chrome 35 when the input field's content is LARGER than the input field itself in as Chrome does not "scroll" to the end of the content. 当输入字段的内容比输入字段本身大时,这在Chrome 35中不再起作用,因为Chrome不会“滚动”到内容的末尾。 It's known that Chrome has problems with input field and JS (this is why there's a Chrome workaround, but it still does not work like expected). 众所周知,Chrome在输入字段和JS方面存在问题(这就是为什么有Chrome解决方法的原因,但是仍然无法按预期工作)。 It works perfectly in Firefox 30. I want this to work also when the content is larger than the input field. 它在Firefox 30中完美运行。当内容大于输入字段时,我希望它也能正常工作。

Questions 问题

Why does this not work under the described circumstances ? 为什么在上述情况下不起作用? A possible fix would also be nice. 可能的修复方法也不错。

I think I solved it like that (quick & dirty). 我想我这样解决(快速又脏)。 See the full JSFiddle here . 这里查看完整的JSFiddle

HTML HTML

<input value="1111111111111111111111111222222222" id="test" />

JS JS

var elem = document.getElementById('test');
elem.focus();
elem.value = "1111111111111111111111111222222222";
elem.scrollLeft = elem.scrollWidth;    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM