输入框焦点定位

背景:有个需求,有个输入价钱的输入框,需要输入框里一直有个元单位,但是保护不妨碍输入

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <script type="text/javascript" src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <meta charset="utf-8" />
</head>
<body>
    <input type="text" onkeyup="press(this)" id="testinput" onfocus="press(this)" value="元" style="text-align:right;"/>
    <script>
        function press(obj)
        {
            var value = $(obj).val();
            value = value.replace('', '') + '';
            $(obj).val(value);
            var len = value.length;
            var index = len - 1;// 焦点在文本中的位置
            set_text_value_position('testinput', len-1);
        }
        function set_text_value_position(obj, spos) {
            var tobj = document.getElementById(obj);
            if (spos < 0)
                spos = tobj.value.length;
            if (tobj.setSelectionRange) { //兼容火狐,谷歌
                setTimeout(function () {
                    tobj.setSelectionRange(spos, spos);
                    tobj.focus();
                }
                    , 0);
            } else if (tobj.createTextRange) { //兼容IE
                var rng = tobj.createTextRange();
                rng.move('character', spos);
                rng.select();
            }
        }

    </script>
</body>
</html>

 

posted @ 2018-11-06 16:13  过一天日子修一天缘  阅读(501)  评论(0编辑  收藏  举报