Home > Web Front-end > JS Tutorial > body text

A simple way to move focus to the last position in js

高洛峰
Release: 2016-12-05 11:52:00
Original
1442 people have browsed it

When the input box (input/textarea) gets focus, move the focus to the end. In some cases, the user experience is good. Most of the methods on the Internet are for IE browser.

The code is as follows:

var el = document.getElementById('txtArticle');
var range = el.createTextRange();
range.moveStart('character', el.value.length);
range.collapse(false);
range.select();
Copy after login

In fact, you can delete the moveStart line, because after the createTextRange method creates the range, you can use the collapse method and the parameter is false to move to the end. collapse(true) moves the cursor to the beginning of the range, collapse(false) moves the cursor to the end of the range. Standard browsers such as Firefox can use w3c's setSelectionRange method.

The code is as follows:

var range, el = document.getElementById('txtPhone');
if (el.setSelectionRange) {
  el.focus();
  el.setSelectionRange(el.value.length, el.value.length)
} else {
  range = el.createTextRange();
  range.collapse(false);
  range.select();
}
Copy after login

Note that the setSelectionRange method only applies to input/textarea elements. The focus of other non-native editable elements can be moved to the collapse method of the selection object,

For example:

var sel, el = document.getElementById('hint');
sel = window.getSelection();
sel.collapse(el, 1);
el.focus();
Copy after login


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template