让输入框获取焦点 JS
发布时间:2015-11-09, 00:56:30 分类:HTML | 编辑 off 网址 | 辅助
正文 408字数 318,053阅读
方法1:<body onload="document.getElementById('inputId').focus()">
Run code
Cut to clipboard
方法2:
function init(){
document.getElementById("inputId").focus();
}
Run code
Cut to clipboard
例如:
<body onload="document.getElementById('test').focus()">
我要获取焦点:<input type="text" name="test" id="test">
</body>
Run code
Cut to clipboard
(支付宝)给作者钱财以资鼓励 (微信)→
有过 1 条评论 »
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title></title> <style> .box{ width: 300px; padding: 30px 20px; background-color: #f4d5e8; margin: 50px; font-size: 24px; color: #ccc; text-align: center; } #box2{ color: #4c9579; background-color: #d5f4e8; } .box:focus{ border: solid 1px #d5e8f4; box-shadow: 0 0 5px 2px #d5e8f4; } </style> </head> <body> <div class="box" id="box1">我不能获得焦点</div> <div class="box" id="box2" tabindex="1">点我可以获得焦点。因为我有【tabindex】属性</div> <script> document.getElementById('box2').onfocus = function(){ this.innerHTML = "现在请敲击键盘!!"; } document.getElementById('box2').onblur = function(){ this.innerHTML = "点我可以获得焦点。因为我有【tabindex】属性"; } //能获得焦点的div才可以使用keypress等键盘事件 document.getElementById('box2').onkeypress = function(e){ this.innerHTML = "只有获得焦点,才能用keypress等事件。您按的是【"+e.key+"】。"; } //没有焦点的div等普通dom元素 就算绑定也没用! document.getElementById('box1').onkeypress = function(e){ alert('就算绑定了也没用!!'); } </script> </body> </html>