简体   繁体   English

如何在 Javascript 中恢复插入符号位置?

[英]How to restore caret position in Javascript?

I am trying to achieve that when the user presses the reset button, the cursor positions back to the beginning of the input.我试图实现当用户按下重置按钮时,光标位置回到输入的开头。

Can anyone guide me on how to achieve this?谁能指导我如何实现这一目标?

在此处输入图片说明

 function restore(){ // here need to set the position };
 p { text-align:left; padding:10px; font-size: 20px; font-family: "Open Sans"; border:1px black solid; } button{ font-size: 25px; }
 <p contenteditable="true"></p> <button onclick="restore()">Restore</button>

You can use Range and Selection objects as described in this answer :您可以使用本答案中所述的RangeSelection对象:

 function restore() { var el = document.getElementById("editable"); var range = document.createRange(); var sel = window.getSelection(); range.setStart(el, 0); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); }
 p { text-align:left; padding:10px; font-size: 20px; font-family: "Open Sans"; border:1px black solid; } button{ font-size: 25px; }
 <p id="editable" contenteditable="true"></p> <button onclick="restore()">Restore</button>

If you can use the Input tag instead of the P tag, this code is appropriate :如果您可以使用 Input 标签而不是 P 标签,则此代码是合适的:

 function myFunction() { var text = document.getElementById("myInput"); text.select(); text.setSelectionRange(text.value.length, text.value.length) }
 button{ font-size: 25px; }
 <input type="text" value="hello" id="myInput"> <button onclick="myFunction()">Copy text</button>

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

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