在js(jquery)中获得文本框焦点和失去焦点的方法

By Heanny
2018-01-10
4531 read

先来看javascript的直接写在了input上代码如下:

<input name="pwuser" type="text" id="pwuser" value="账号" onBlur="if(this.value=="") this.value="账号";" onFocus="if(this.value=="账号") this.value="";" />
<input name="pwpwd" type="password" 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("搜神马?");
    });
})
孤独
vue 的 history 模式(去掉#)

Comments

暂无评论,还不快来坐沙发...

Leave a Reply