第一次如何清除焦点输入?

时间:2013-08-29 16:02:11

标签: javascript html

我有2个输入:

<input type="text" value="username">
<input type="password" value="password">

如果我在特定输入中,我想删除默认值(只是第一次)。我有这样的JavaScript添加属性:

onfocus="this.value='';"

但是每次关注它都会清楚输入。如何在第一次关注它时清除输入?

7 个答案:

答案 0 :(得分:8)

您想要的是一个占位符:一个自动删除的默认值。

如果您可以接受占位符not visible for IE9- users,请执行以下操作:

<input type="text" placeholder="username">

如果您需要与IE9兼容,请使用one of the many polyfills,人们已经为您处理了实施细节。

答案 1 :(得分:5)

只需在输入中使用占位符,例如

<input type="text" placeholder="username">

为每个输入命名都是好的,所以:

<input type="text" name="username" placeholder="username">

答案 2 :(得分:1)

尝试

onfocus="if(this.flag == undefined){ this.flag = true; this.value=''; }"

答案 3 :(得分:0)

试试这样: -

$('.text').focus(function() {
    if (this.value == this.value) {
        $(this).val("");
    }
}).blur(function() {
    if (this.value == "") {
        $(this).val(this.value);
    }
});

http://jsfiddle.net/32Tns/296/

答案 4 :(得分:0)

只需检查您的onfocus功能

    onfocus="if(this.value == 'username'){this.value='';}"


<input type="text" value="username" onfocus="if(this.value == 'username'){this.value='';}">
    <input type="password" value="password" onfocus="if(this.value == 'password'){this.value='';}">

JSFIDDLE EXAMPLE

答案 5 :(得分:0)

<input type="text" value="username" id="username" title="username" />

$( '#username' ).bind({
    'focus': function( event ) {
       $( this ).val( '' );
    },
    'blur': function( event ) {
       var obj = $( this ),
           title = obj.attr( 'title' );
       obj.val( title );
    }
})

答案 6 :(得分:0)

如果你正在使用jQuery,你可以使用它:

<input type="text" name="username" value="username" />

使用Javascript:

$('input[name=username]').one('focus', function() {
    $(this).val('');
});

.one()只会触发绑定事件一次