JS控制光标选中文本和检测文本是否为数字

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/RodeStillFaraway/article/details/78611733

找到一篇比较详细的JS控制光标: https://www.cnblogs.com/xupeiyu/p/5985598.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script type="text/javascript">

        // 焦点离开做数字检测,重置为0并选中
        function Textbox_onblur(pElement){
            var tElementId = pElement.id;
            if(checkIsNum(tElementId)==false){
                pElement.value = 0;
                setSelectTextAll(tElementId);
                pElement.style.backgroundColor="#FF0000";
                pElement.focus();
            }else{
                pElement.style.backgroundColor="#FFFFFF";
            }
        }

        //数字检测
        function checkIsNum(pElementId){
            var tNumber=document.getElementById(pElementId).value;

            if (!(/^(-)?(([1-9]{1}\d*)|([0]{1}))(\.(\d){1,4})?$/.exec(tNumber))) {
                return false; // 非数字
            }

            return true;
        }

        //选中指定控件所有文本
        function setSelectTextAll(pElementId){
            var tElementValue = document.getElementById(pElementId).value;

            setSelectText(pElementId,0,tElementValue.length);
        }

        //选中指定控件指定位置文本
        function setSelectText(p_el,p_start,p_end){
            var tElement = document.getElementById(p_el);

            // 设置光标
            if(tElement.createTextRange){
                var Range=tElement.createTextRange();
                Range.collapse();
                Range.moveEnd('character',p_end);
                Range.moveStart('character',p_start);
                Range.select();
            }

            // 光标选中
            if(tElement.setSelectionRange){
                    tElement.focus();  
                    tElement.setSelectionRange(p_start,p_end);  //设光标选中位置 
                }
            }
    </script>
</head>


<body>
    测试选中全部文本<br>
    <input id="Textbox1" type="text"  />
    <input type="button"  style="width:125px;height:25px;" value = "点击选中全部文本" onclick="setSelectTextAll('Textbox1')" ></button>
    <br>
    <br>
    光标离开检测是否为数字,非数字加红底色并重置为数字0<br>
    <input id="Textbox" type="text" onblur="Textbox_onblur(this)" />
    
</body>
</html>




猜你喜欢

转载自blog.csdn.net/RodeStillFaraway/article/details/78611733