Last active
August 29, 2015 13:59
-
-
Save zfkun/10957431 to your computer and use it in GitHub Desktop.
cursor position setting
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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