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


当前回答

在jQuery中,这是

$(document).ready(function () {
  $('input').focus(function () {
    $(this).attr('value',$(this).attr('value'));
  }
}

其他回答

拿出一些答案。制作单行jquery。

$('#search').focus().val($('#search').val());
<input id="input_1">
<input id="input_2" type="hidden">

<script type="text/javascript">
//save input_1 value to input_2
$("#input_2").val($("#input_1").val());

//empty input_1 and add the saved input_2 into input_1
$("#input_1").val("").val($("#input_2").val()).focus();
</script>

我从这里得到了最好的答案,并创建了一个在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">

试试这个,它对我很有效:

//input is the input element

input.focus(); //sets focus to element
var val = this.input.value; //store the value of the element
this.input.value = ''; //clear the value of the element
this.input.value = val; //set that value back.  

为了让光标移动到最后,输入必须先有焦点,然后当值改变时,它才会移动到最后。如果你将.value设置为相同的值,它在chrome中不会改变。

现在是2019年,上面的方法对我来说都没用,但这个方法管用,摘自https://css-tricks.com/snippets/javascript/move-cursor-to-end-of-input/

函数moveCursorToEnd(id) var el = document.getElementById(id) el.focus () If(类型的el。selectionStart == "number") { 埃尔。selectionStart = el。selectionEnd = el.value.length; } else if(类型的el。createTextRange != "undefined") { var range = el.createTextRange(); range.collapse(假); range.select (); } } <input id="myinput" type="text" /> <a href="#" onclick="moveCursorToEnd('myinput')>移动光标到结束</a> .