Skip to content

Instantly share code, notes, and snippets.

@zfkun
Last active August 29, 2015 13:59
Show Gist options
  • Save zfkun/10957431 to your computer and use it in GitHub Desktop.
Save zfkun/10957431 to your computer and use it in GitHub Desktop.
cursor position setting
/**
* @file 简易光标定位
* @author zfkun([email protected])
*/
/**
* 简易光标定位
*
* @param node {(HTMLTextAreaElement | HTMLInputElement)} `TextArea`或`Input`元素
* @param index {number=} 定位位置,不传则定位到末尾
*/
function setCursorTo( node, index ) {
index = arguments.length > 1
? Math.min( Math.max( 0, parseInt( index, 10 ) || 0 ), node.value.length )
: node.value.length;
if ( document.selection ) {
var r = node.createTextRange();
r.move( 'character', index );
r.select();
}
else {
node.setSelectionRange( index, index );
node.focus();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment