【问题标题】:CSS / HTML - Focus automatically leaves input field for no reasonCSS / HTML - 焦点无缘无故自动离开输入字段
【发布时间】:2013-11-25 22:57:15
【问题描述】:

我有一个使用下面的 css 布局的表单。大多数情况下,它运行良好,但只要有两个带有<label> 标签的输入字段,我就无法单击以选择第二个字段。 如果单击第一个输入字段就可以了。如果您单击第二个输入字段,它会自动将焦点跳回第一个。 但是,您可以成功地在两者之间切换。

div.largeblock{
    margin:5px 0px 20px 0px;
    background:#d7e5f2;
    border:1px solid #d7e5f2;
}
div.largeblock label{
    display:block;
    margin-bottom:5px;
}
div.largeblock label span{
    display:block;
    float:left;
    margin-right:6px;
    width:130px;
    text-align:right;
}
<label>
   <span>Postcode</span>
   <input type="text" maxlength="4" name="postcode1" required="required" placeholder="Post" />
   <input type="text" maxlength="3" name="postcode2" required="required" placeholder="Code"/>
</label>

我有同样的问题,我在 1 个标签内有 &lt;select&gt;&lt;input&gt;。但是对于其他 20 行左右只有 1 个 &lt;input&gt; 来说没关系。

【问题讨论】:

标签: html css layout input-field


【解决方案1】:

当您点击label 时,大多数浏览器的行为是将焦点(或在复选框的情况下选中)给相关输入。

您需要将第二个input 标记移出label 标记。可能是它自己的。

【讨论】:

  • 谢谢你,马修。所以在我看来,我遵循的建议使用
  • @showdev 谢谢。但是如果 HTML 进入
    那么它会拆分行。 jsfiddle.net/64CKm/1
  • 您希望标签为“内联”(或浮动)。从div.largeblock label 中删除display:blockjsfiddle.net/64CKm/2
  • @user2990014 :概念是labels 不仅仅是布局的普通标签。 label 标签自动将 input 聚焦在其中,当您有 2 个 input 框时,这是一个问题。尝试使 inputs display: inline-block; 使框对齐。
【解决方案2】:

label 元素应引用单个 input 元素,使用 for 属性,该属性应具有与它所引用的 input 元素的 id 相同的 value。否则,它的行为将无法预测,就像您的示例中 label 聚焦第一个 input 一样,这在您的示例中没有任何意义。如果要对表单元素进行分组,则应使用元素 fieldset(可以使用 css 设置样式,使其看起来像 label)。

正确的语法是:

<label for="postcode1">Postcode 1</label>
<input type="text" id="postcode1" maxlength="4" name="postcode1" required="required" placeholder="Post" />
<label for ="postcode2">Postcode 2</label>
<input type="text" id="postcode2" maxlength="3" name="postcode2" required="required" placeholder="Code"/>

或者如果你想使用fieldset:

<fieldset>
    <legend>Postcode</legend>
    <input type="text" maxlength="4" name="postcode1" required="required" placeholder="Post" />
    <input type="text" maxlength="3" name="postcode2" required="required" placeholder="Code"/>
</fieldset>

【讨论】:

    猜你喜欢
    相关资源
    最近更新 更多
    热门标签