//设定选中范围
someInput.setSelectionRange(0, 2);
//只读
<input type="text" value="2" readonly />
//绑定键盘输入事件
someInput.addEventListener('keydown', function (event) {
//......
});
//获取光标位置
<input type="text" id="text-element" />
<!-- Or a textarea
<textarea id="text-element"></textarea>
-->
<input type="button" id="trigger" value="Check"/>
<script>
document.getElementById("trigger").addEventListener("click", function(){
var myElement = document.getElementById('text-element');
var startPosition = myElement.selectionStart;
var endPosition = myElement.selectionEnd;
// Check if you've selected text
if(startPosition == endPosition){
alert("The position of the cursor is (" + startPosition + "/" + myElement.value.length + ")");
}else{
alert("Selected text from ("+ startPosition +" to "+ endPosition + " of " + myElement.value.length + ")");
}
},false);
</script>