什么是最好的方法(我假设最简单的方法),以放置光标在文本的输入文本元素的末尾通过JavaScript -焦点已设置到元素?


当前回答

document.querySelector(“输入”)。addEventListener('focus', e => { Const {value} = e.target; e.target.setSelectionRange(价值。长度,value.length); }); <input value="my text" />

其他回答

我从这里得到了最好的答案,并创建了一个在Chrome中工作良好的功能。

您需要将逻辑封装在一个超时中,因为您必须等待焦点完成后才能访问所选内容 要将光标放在末尾,选择起始点需要放在末尾 为了滚动到输入字段的末尾,scrollLeft需要匹配scrollWidth

/** * Upon focus, set the cursor to the end of the text input * @param {HTMLInputElement} inputEl - An HTML <input> element */ const setFocusEnd = (inputEl) => { setTimeout(() => { const { scrollWidth, value: { length } } = inputEl; inputEl.setSelectionRange(length, length); inputEl.scrollLeft = scrollWidth; }, 0); }; document .querySelector('input') .addEventListener('focus', (e) => setFocusEnd(e.target)); html, body { width: 100%; height: 100%; margin: 0; } body { display: flex; flex-direction: column; justify-content: center; align-items: center; } input:focus { background-color: hsla(240, 100%, 95%, 1.0); } <input type="text" placeholder="Search..." value="This is some really, really long text">

我在IE中遇到了同样的问题(在通过RJS/prototype设置焦点后)。 当该字段已经有一个值时,Firefox已经在末尾留下了光标。IE将光标强制移到文本的开头。

我得出的解决方案如下:

<input id="search" type="text" value="mycurrtext" size="30" 
       onfocus="this.value = this.value;" name="search"/>

这在IE7和FF3中都有效,但在现代浏览器中不起作用(见评论),因为没有指定UA必须覆盖这种情况下的值(根据元策略编辑)。

<script type="text/javascript">  
    function SetEnd(txt) {  
      if (txt.createTextRange) {  
       //IE  
       var FieldRange = txt.createTextRange();  
       FieldRange.moveStart('character', txt.value.length);  
       FieldRange.collapse();  
       FieldRange.select();  
       }  
      else {  
       //Firefox and Opera  
       txt.focus();  
       var length = txt.value.length;  
       txt.setSelectionRange(length, length);  
      }  
    }   
</script>  

我在IE9和Firefox 6中使用了这个功能。和Opera 11.x

尝试使用Vanilla JavaScript。

<input type="text" id="yourId" onfocus="let value = this.value; this.value = null; this.value=value" name="nameYouWant" class="yourClass" value="yourValue" placeholder="yourPlaceholder...">

在Js

document.getElementById("yourId").focus()

检查这个解决方案!

//fn setCurPosition $.fn.setCurPosition = function(pos) { this.focus(); this.each(function(index, elem) { if (elem.setSelectionRange) { elem.setSelectionRange(pos, pos); } else if (elem.createTextRange) { var range = elem.createTextRange(); range.collapse(true); range.moveEnd('character', pos); range.moveStart('character', pos); range.select(); } }); return this; }; // USAGE - Set Cursor ends $('#str1').setCurPosition($('#str1').val().length); // USAGE - Set Cursor at 7 position // $('#str2').setCurPosition(7); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <p>Set cursor at any position</p> <p><input type="text" id="str1" value="my string here" /></p> <p><input type="text" id="str2" value="my string here" /></p>