如何用JS让一个输入框获得焦点

JavaScript015

如何用JS让一个输入框获得焦点,第1张

让输入框获取焦点:

方法1:<body onload="document.getElementById('inputId').focus()">

方法2:

function init(){

document.getElementById("inputId").focus()

}

例如:

<body onload="document.getElementById('test').focus()">

我要获取焦点:<input type="text" name="test" id="test">

</body>

需要准备的材料分别是:电脑、html编辑器、浏览器。

1、首先,打开html编辑器,新建html文件,例如:index.html。

2、在index.html的<script>标签中,输入js代码:

$('body').append(document.activeElement.id == "a" ? 'true': 'false')

$('#a').focus(function () {

$('body').append(document.activeElement.id == "a" ? 'true': 'false')

})

3、浏览器运行index.html页面,此时会发现false代表没有聚焦,点击聚焦后发现打印了true。

<html>

<head>

<script type="text/javascript">

function setFocus()

  {

  document.getElementById('password1').focus()

  }

function loseFocus()

  {

  document.getElementById('password1').blur()

  }

</script>

</head>

<body>

<form>

<input type="password" id="password1" value="thgrt456" />

<input type="button" onclick="setFocus()" value="Set focus" />

<input type="button" onclick="loseFocus()" value="Lose focus" />

</form>

</body>

</html>