javascript输入焦点

时间:2011-03-16 03:29:53

标签: javascript css placeholder

<form id="commentform" method="post" action="wp-comments-post.php">
    <input type="text" aria-required="true" tabindex="1" size="22" value="" 
       id="author" name="author">
</form>

我将默认值“visitor”设置为输入框。当焦点在文本框中或mouose进入时,我想隐藏“访问者”字符串,并希望在它失去焦点或mose移出时显示它。

5 个答案:

答案 0 :(得分:1)

尝试使用HTML5占位符属性:

<input type="text" aria-required="true" tabindex="1" size="22"
    placeholder="visitor" id="author" name="author">

虽然浏览器支持还不是100%,但这将为您提供一种标准方法来实现您想要实现的目标,而不会经历不必要的环节。

你可以尝试的另一件事是将输入元素叠加在某些文本上,使其在不在焦点时透明/半透明,在焦点/填充时使其不透明。

截至今天,Tumblr的登录页面使用了这个技巧:

<div class="input_wrapper" id="">
    <label for="user_password">Password</label>
    <input type="password" id="user_password" name="user[password]" data-validation-type="password" value="">
</div>

通过CSS魔法变为:

enter image description here

答案 1 :(得分:1)

看起来您正在使用WordPress,因此您的网站上有jQuery库。

您可以使用我的jQuery plugin来实现此目标。

实施例

Example

的jQuery

$('#author').inputLabel({
   customLabel: 'Visitor'
});

在这种情况下,我必须自己指定标签,但是插件可以通过找到label的相关input元素来实现,而{{1}}元素应该存在以供访问。

jsFiddle

答案 2 :(得分:0)

如果您还在使用HTML 5,请尝试以下操作:

<script type="text/javascript">
var prompt="visitor";       
var txt=document.getElementById("author");
txt.onfocus=function(){txt.value='';}
txt.onblur=function(){
            if(txt.value==''){
                txt.value=prompt;
            }
        }
</script>

答案 3 :(得分:0)

Ates Goral的回答看起来非常有趣。请先尝试一下。如果你不想出汗,这是另一种选择.. :) 我建议使用水印插件。有很多可用的 之前使用过this plugin。工作得很好。给你很好的控制。
该插件需要jQuery

答案 4 :(得分:0)

虽然我也会使用jQuery或CSS和伪类(:focus)....

这是一个简单的JS解决方案,可以完全满足您的需求。同样,我不建议将此方法用于一个或两个以上的输入字段。

<input type="text" value="Visitor" onFocus="this.value='';" onBlur="this.value='Visitor';" id="author"/>