js中<input>如何获得焦点?

JavaScript018

js中<input>如何获得焦点?,第1张

用自带的focus()就可以了

利用js中<input/>实现文本框默认获取输入焦点完整代码实现如下:

<html>

 

<head>

     

<meta http-equiv="Content-Type" content="text/htmlcharset=ISO-8859-1">

                  <title>Insert title here</title>

   

<script type="text/javascript">       

//输入框获取鼠标焦点       

function autoFocus(){

           

var pFocus = document.getElementById("password")

pFocus.focus()

   

pFocus.select()

   

}    

</script>

 

</head>

 

<body onload="autoFocus()">

     

<div id="loginform">

     

<h1 style="font-size:1.5empadding:20px">输入密码</h1>

     

<form action="${pageContext.request.contextPath}/" method="post">

   

<input id="password" type="password" name="password">

 

<input type="submit" value="提交">

   

</form>

   

</div>

 

</body>

</html>

扩展资料:

JavaScript 使我们有能力创建动态页面。事件是可以被 JavaScript 侦测到的行为。 网页中的每个元素都可以产生某些可以触发JavaScript函数的事件。比方说,我们可以在用户点击某按钮时产生一个 onClick 事件来触发某个函数。事件在 HTML 页面中定义 。

参考资料:

JavaScript官方API接口-:focus

百度百科-JavaScript

W3cschool-获得字段焦点

$(function(){

$(":text").focus(function(){

this.select()

})

})

JQuery文本框获得焦点背景颜色改变:

1.先使用jQuery选择器找到所有的文本框。

2.为文本框注册获得焦点事件,即focus事件。

3.在焦点事件的事件处理函数中对当前得到焦点的文本框设置背景色。

4.注册失去焦点事件,即blur事件。

5.在失去焦点的事件处理函数中对当前触发事件的文本框改变背景颜色。

<script type="text/javascript">

$(function(){

//找到文本框,并注册得到焦点事件。

$("input:text").focus(function(){

//让当前得到焦点的文本框改变其背景色。

$(this).css("background","pink")

})

//找到文本框,并注册失去焦点事件

$("input:text").blur(function(){

//让当前失去焦点的文本框背景色变为白色。

$(this).css("background","white")

})

})

</script>

让输入框获取焦点:

方法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>