javascript-跨浏览器选中文本框指定长度的值

跨浏览器实现选中文本框指定的长度的值

可用于编辑器的功能的开发。

依赖

  • EventUtil.js

代码

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>10.cross-browser-selectText</title>
        <script src="EventUtil.js"></script>
        <style>
            ul,li{
                list-style:none;
            }
        </style>
    </head>
    <body>
        <form name="myform">
            <label for="name">姓名:</label>
            <input type="text" name="name" autofocus id="name" placeholder="请输入姓名" value="我在哪里"><br>
            <input type="button" value="select-btn" id="select-btn"/>
        </form>
        <script>
            (function(){
                var form = document.forms['myform']
                var elements = form.elements
                var inputText = elements['name']


                var btn = document.querySelector('#select-btn')
                EventUtil.addHandler(btn, 'click', function(event){
                    inputText.focus()
                    selectText(inputText, 0, 1)
                })

                // 在文本框中看到文本被选中的效果(必须让文本框获取焦点)
                function selectText(textbox, startIndex, stopIndex){
                    if (textbox.setSelectionRange){
                        textbox.setSelectionRange(startIndex, stopIndex);
                    } else if (textbox.createTextRange){
                        var range = textbox.createTextRange();
                        range.collapse(true);
                        range.moveStart("character", startIndex);
                        range.moveEnd("character", stopIndex - startIndex);
                        range.select();                    
                    }
                    textbox.focus();
                }
            })()
        </script>
    </body>
</html>

效果如下:

这里写图片描述

猜你喜欢

转载自blog.csdn.net/harmsworth2016/article/details/80370393