How do I shift the visible text in a narrow input element to see the cursor at the end?

后端 未结 2 815
被撕碎了的回忆
被撕碎了的回忆 2020-12-11 09:40

The problem I am having is that given an input element with a maxlength that is much wider than the element\'s width (as set in its style), and, given a value that is wider

相关标签:
2条回答
  • 2020-12-11 10:06

    I doubt this is a great cross-browser solution, however it does seem to be a work around in Firefox. I originally tried it by simulating the right arrow-key press, but didn't have any luck.

    function setCursor(id)
    {
        var elem = document.getElementById(id);
    
        elem.focus();
        elem.setSelectionRange(elem.value.length, elem.value.length);
    
        // Trigger a "space" keypress.
        var evt = document.createEvent("KeyboardEvent");
        evt.initKeyEvent("keypress", true, true, null, false, false, false, false, 0, 32);
        elem.dispatchEvent(evt);
    
        // Trigger a "backspace" keypress.
        evt = document.createEvent("KeyboardEvent");
        evt.initKeyEvent("keypress", true, true, null, false, false, false, false, 8, 0);
        elem.dispatchEvent(evt);
    }
    

    More info on initKeyEvent here.

    0 讨论(0)
  • 2020-12-11 10:31

    It is a kludge, but it works:

    Edit: further kludged to actually work:

    <html>
      <head>
        <title>input cursor position</title>
        <script language='javascript'>
    function setatend() {
        var save = document.getElementById("mytextbox").value;
        mytextbox.focus(); 
        mytextbox.value = save; 
    }
    function setfocus() {
        var box = document.getElementById("mytextbox");
        box.focus();    
    }
    </script>
      </head>
          <body onload='setfocus();'>
        <input onfocus='setatend();' id='mytextbox' maxlength='200' value='some very very very very very long text' style='width: 100px;'></input>
      </body>
    </html> 
    
    0 讨论(0)
提交回复
热议问题