Home  >  Article  >  Web Front-end  >  Position the cursor on the rightmost side of the input box to implement the code_Basic knowledge

Position the cursor on the rightmost side of the input box to implement the code_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 17:47:231183browse

Scenes like this are often needed in the front-end development process. Use JS to position the cursor on the rightmost side of the input box.

Scene 1: Edit the description text of the picture


Scenario 2: Ajax.InPlaceEditor class of Script.aculo.us. Double-click to edit, and leave after editing to automatically update the area.

The above scenarios all require JS to position the cursor on the rightmost side of the input box, but not click into the input box through the mouse.

We know that the most basic method of implementation is the focus method of HTMLElement. As follows

Copy code The code is as follows:




<script> <br>var input = document.getElementsByTagName('input')[0]; <br>input.focus (); <br></script>
 

When you open this page, you will find that the cursor is located on the far left side of the input box. The effect is as follows

What we need to achieve now is to position the cursor on the rightmost side of the input box, which requires three steps.

1, call the focus method

2, value assignment is empty

3, assign the value of the previous input to yourself

Copy code The code is as follows:




<script> <br>var input = document.getElementsByTagName('input')[0]; <br>var val = input.value; <br>input.focus(); <br>input.value = ''; <br>input.value = val; <br></script>

Run The final effect is as shown in the figure, the cursor is on the far right side of the depth box

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn