javascript中怎么设置文本框获得焦点

JavaScript073

javascript中怎么设置文本框获得焦点,第1张

代码如下:

<input name="pwuser" type="text" id="pwuser" class="input" value="楼盘账号" onBlur="if(this.value=='') this.value='楼盘账号'" onFocus="if(this.value=='楼盘账号') this.value=''" />

<input name="pwpwd" type="password" class="input1" value="******" onBlur="if(this.value=='') this.value='******'" onFocus="if(this.value=='******') this.value=''">

jquery实现方法

对于元素的焦点事件,我们可以使用jQuery的焦点函数focus(),blur()。

focus():得到焦点时使用,和javascript中的onfocus使用方法相同。

如:

代码如下:

$("p").focus()或$("p").focus(fn)

blur():和onblur一样。

如:

代码如下:

$("p").blur()或$("p").blur(fn)

实例

代码如下:

<form>

<label for="searchKey" id="lbSearch">搜神马?</label>这里label覆盖在文本框上,可以更好的控制样式

<input id="searchKey" type="text" />

<input type="submit" value="搜索" />

</form>

jquery代码

代码如下:

$(function() {

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

$('#lbSearch').text('')

})

$('#searchKey').blur(function() {

var str = $(this).val()

str = $.trim(str)

if(str == '')

$('#lbSearch').text('搜神马?')

})

})

$(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>

需要准备的材料分别是:电脑、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。