首页

Javascript

Html
Css
Node.js
Electron
移动开发
小程序
工具类
服务端
浏览器相关
前端收藏
其他
关于
公司注册

js移动光标到文字末尾

2013年07月28日 发布 阅读(2757) 作者:Jerman

移动光标到文字末尾,如果使用<input><textarea>时,需要把光标定位在文字的后面。

一种方法是使用重置value为空,再设置value的方法,方法简单,但偶尔会看到文字闪动一下。

  1. function moveCursorToEnd(el) {
  2. var value =this.value;
  3. el.value = "";
  4. el.focus()
  5. el.value = value;
  6. }

另一种方法,建议使用这个方法:

  1. function moveCursorToEnd(el){
  2. el.focus();
  3. if (typeof el.selectionStart == "number") {
  4. el.selectionStart = el.selectionEnd = el.value.length;
  5. } else if (typeof el.createTextRange != "undefined") {
  6. var range = el.createTextRange();
  7. range.collapse(false);
  8. range.select();
  9. }
  10. }
版权声明:本站文章除特别声明外,均采用署名-非商业性使用-禁止演绎 4.0 国际 许可协议,如需转载,请注明出处