JavaScript 选择input光标所在位置 设置input的内容选中并得到选中的值

做日历控件时,需要实现按—>实现右移并选中日期部分内容,yyyy-mm-dd hh:mm:ss,以年、月、日、时分秒为单位选中,下面是用到的小程序
选择input光标所在位置
function getTxt1CursorPosition(){
var oTxt1 = document.getElementById("txt1");
var cursurPosition=-1;
if(oTxt1.selectionStart){//非ie浏览器
cursurPosition= oTxt1.selectionStart;
}else{//ie
var range = document.selection.createRange();
range.moveStart("character",-oTxt1.value.length);
cursurPosition=range.text.length;
}
alert(cursurPosition);
}
    设置input里的某块内容被选中(开始:startIndex  结束:endIndex)
        function setSelectionRange() {
            if ($input[0].setSelectionRange) { //firefox chrome
                $input[0].focus();
                $input[0].setSelectionRange(startIndex, endIndex);
            }
            else if ($input[0].createTextRange) {  //IE
                var range = $input[0].createTextRange();
                range.collapse(true);
                range.moveEnd('character', endIndex);
                range.moveStart('character', startIndex);
                range.select();
            }
        }
得到input里选中的值
        function getInputSelection() {
            var myArea = $input[0];
            var selection;
            if (myArea.selectionStart) {
                if (myArea.selectionStart != undefined) {
                    selection = myArea.value.substr(myArea.selectionStart, myArea.selectionEnd - myArea.selectionStart);
                }
            } else {
                if (window.getSelection) {  //非ie浏览器,firefox,safari,opera
                    selection = window.getSelection();
                } else if (document.getSelection) {
                    selection = document.getSelection();
                } else if (document.selection) {
                    selection = document.selection.createRange().text;
                }
            }
            return selection;
        }

你可能感兴趣的:(JavaScript应用)