html - Bootstrap 在未显示占位符时选择标签

标签 html css twitter-bootstrap

在 float 标签的示例页面中,有一个用于未显示占位符的标签选择器:

.form-label-group input:not(:placeholder-shown) ~ label {
  padding-top: calc(var(--input-padding-y) / 3);
  padding-bottom: calc(var(--input-padding-y) / 3);
  font-size: 12px;
  color: #777;
}

这个选择器基于这个 HTML 结构:

<div class="form-label-group">
   <input type="email" id="inputEmail" class="form-control" placeholder="Email">
   <label for="inputEmail">Email</label>
</div>

我有一个带有输入的标签,它在这个结构中:

<div id="" class="form-label-group ">
   <div class="form-before-field">
   </div>
   <div class="form-field">
      <div id="form-wrap" class="field-wrap" data-field-id="1">
         <div class="field-label">
            <label for="field-1" class="">Name </label>
         </div>
         <div class="field-element">
            <input type="text" value="" class="forms-field form-control" placeholder="Name" id="field-1" name="field-1" aria-invalid="false" aria-describedby="error-1">
         </div>
      </div>
   </div>
   <div class="after-field">
      <section>
      <div class="input-limit"></div>
      <div id="error-1" class="error-wrap error" role="alert"></div>
      </section>
   </div>
</div>

当未显示占位符时,我应该使用什么选择器来定位标签?

最佳答案

具体问题:

由于您的 HTML 结构,您需要转义出 <div class="field-element">然后找到之前的<div class="field-label"> .可悲的是,两者都没有 parent selector 也不是 'previous' selector 在 CSS 中。因此,不可能定位您的 <label>基于你占位符的 <input>使用纯 CSS。

说了这么多,我也会在这个答案上留下更通用的方法,因为这实际上是一个相当普遍的请求,而且我相信有人会用更传统的结构偶然发现这个问题:)


一般定位 <label>基于 <input>占位符:

您可能认为可以使用简单的 :empty 为此伪类,但不幸的是,情况并非如此。这是因为 <input> void element ,因此,内容模型始终为空。

目前唯一的纯 CSS 方法是使用 :placeholder-shown 伪类。这可以与 :not 结合使用<input> 为目标占位符不存在时的元素。

去定位对应的 <label> ,您可以将其与 adjacent sibling combinator ( + ) 结合使用 定位输入后立即出现的标签。

总而言之,您正在寻找:

input(:placeholder-shown) + label

可以在下面看到:

input + label {
  display: none; /* Hidden by default for the sample */
}

input:not(:placeholder-shown) + label {
  display: block;
}
<input id="email" placeholder="Email">
<label for="email">Placeholder Not Shown!</label>

但是请注意,:placeholder-shown目前是not supported在 Internet Explorer 或 Edge 中。在这些浏览器添加对 :placeholder-shown 的支持之前,您将不得不求助于 JavaScript 解决方案。

关于html - Bootstrap 在未显示占位符时选择标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49000446/

相关文章:

javascript - 普通 Javascript 插件在控制台中返回错误

javascript - 每 30 秒用另一个 div 替换一个 div

html - 无法弄清楚如何设置文本样式

jquery - 自动从文本框发送输入数据

css - Twitter Bootstrap - 使用 media-grip 的标题

javascript - 如何使下拉菜单展开单击按钮元素?

javascript - Firefox 和 Opera 中的父 div 宽度为 0,即使我有 child

html - 单击我的博客后,页面顶部的博客标签文本变小/不同。我如何解决它?

javascript - 单击时如何更改按钮的颜色,即使重新加载也始终保持激活状态

javascript - AngularJS:动态维护进度条列表