在页面加载时,我想将光标移动到一个特定的字段。没问题。但是我还需要选择并突出显示放置在该文本字段中的默认值。
来自 http://www.codeave.com/javascript/code.asp?u_log=7004:
var input = document.getElementById('myTextInput'); input.focus(); input.select();
<input id="myTextInput" value="Hello world!" />
在页面加载时执行:
window.onload = function () { var input = document.getElementById('myTextInput'); input.focus(); input.select(); }
在您的 input 标记中,放置以下内容:
onFocus="this.select()"
我发现了一个非常简单的方法,效果很好:
<input type="text" onclick="this.focus();this.select()">
试试这个。这将工作在 Firefox 和 chrome 上。
<input type="text" value="test" autofocus onfocus="this.select()">
在使用 jquery 时..。
Html:
<input type='text' value='hello world' id='hello-world-input'>
Jquery:
$(function() { $('#hello-world-input').focus().select(); });
例子: https://jsfiddle.net/seanmcmills/xmh4e0d4/
var input = document.getElementById('myTextInput'); input.focus(); input.setSelectionRange( 6, 19 );
<input id="myTextInput" value="Hello default value world!" />
select particular text on textfield
Also you can use like
input.selectionStart = 6; input.selectionEnd = 19;
使用 autofocus属性可以很好地处理文本输入和复选框。
autofocus
<input type="text" name="foo" value="boo" autofocus="autofocus"> FooBoo <input type="checkbox" name="foo" value="boo" autofocus="autofocus"> FooBoo
让输入文本字段在页面加载时自动获得焦点:
<form action="/action_page.php"> <input type="text" id="fname" name="fname" autofocus> <input type="submit"> </form>
资料来源: https://www.w3schools.com/tags/att_input_autofocus.asp
在您的输入标记中使用自动对焦,如下所示
<input type="text" autofocus>