CSS输入:焦点用法

时间:2013-12-23 00:45:54

标签: html css html5 css3

尝试获取要显示的范围:用户单击文本字段时阻止。但它没有显示,有人看到我的代码有问题吗?

请参阅小提琴http://jsfiddle.net/WN22k/

CSS

span {
    display:none;
}
input:focus span{
    display:block;
}

HTML

 <div>Password: <input type='password' name='password' maxlength="100"> <span class="help">...password message...</span></input></div>

3 个答案:

答案 0 :(得分:5)

正如克里斯所说,你不能生育<input>元素的孩子。

请改为尝试:

HTML:

<div>Password:
    <input type="password" name="password" maxlength="100" />
    <span class="help">...password message...</span>
</div>

CSS:

.help {display:none}
input:focus~.help {display:block}

请注意,您可能需要display:inlinedisplay:inline-block,具体取决于您正在做的事情。

答案 1 :(得分:1)

Spans不能是输入的子元素,您的标记无效。

通常,如果您要添加某种上下文消息,您可以:

A)将其添加为输入的值,然后在输入获得焦点后立即用javascript清除它

B)将信息写在旁边或作为工具提示

答案 2 :(得分:1)

虽然你的加价无效,但我有一个可行的解决方案。它需要一点jQuery,但足够灵活,可以满足您的需求:

View fiddle

我冒昧地修复你的HTML:

<label for="password">Password: </label>
<input type="password" class="help" id="password" name="password" maxlength="100" rel="help_password" />
<span id="help_password" class="message">...password message...</span>

要遵守WCAG标准,您的输入字段需要相关标签。我还添加了一个rel属性,该值应与相应帮助消息的ID属性的ID标记匹配。

还有一点点jQuery:

$(document).ready(function(event) {
    $('input.help').focus(function(event) {
    $('#' + $(this).attr('rel')).show();
});    
$('input.help').blur(function(event) {
    $('#' + $(this).attr('rel')).hide();
   }); 
});

您可以自动切换包含“help”类和相应帮助消息span标记的任何字段的帮助消息。