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


当前回答

试试下面的代码:

$('input').focus(function () {
    $(this).val($(this).val());
}).focus()

其他回答

仍然需要中间变量,(参见var val=) 否则光标的行为很奇怪,我们需要它在最后。

<body onload="document.getElementById('userinput').focus();">
<form>
<input id="userinput" onfocus="var val=this.value; this.value=''; this.value= val;"
         class=large type="text" size="10" maxlength="50" value="beans" name="myinput">
</form>
</body>

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">

设置光标时,点击文本区域的文本结束… 这段代码的变体是…也工作!Firefox, IE, Safari, Chrome..

在服务器端代码中:

txtAddNoteMessage.Attributes.Add("onClick", "sendCursorToEnd('" & txtAddNoteMessage.ClientID & "');")

在Javascript中:

function sendCursorToEnd(obj) {
    var value =  $(obj).val(); //store the value of the element
    var message = "";
    if (value != "") {
        message = value + "\n";
     };
    $(obj).focus().val(message);
    $(obj).unbind();
 }

我喜欢接受的答案很多,但它停止工作在Chrome。在Chrome浏览器中,光标要走到最后,需要改变输入值。解决方法如下:

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