简体   繁体   中英

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 :

 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 :

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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