跨浏览器实现选中文本框指定的长度的值
可用于编辑器的功能的开发。
依赖
代码
<!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>
效果如下: