如何在输入日期字段中模拟占位符功能?

Shk*_*rik 41 html html5

在日期字段上使用占位符是不可能的,但我确实需要它.

我想要两个日期输入,每个输入文本"From"和"To"作为占位符.

Rom*_*man 88

我正在使用以下CSS技巧:

  input[type="date"]:before {
    content: attr(placeholder) !important;
    color: #aaa;
    margin-right: 0.5em;
  }
  input[type="date"]:focus:before,
  input[type="date"]:valid:before {
    content: "";
  }
Run Code Online (Sandbox Code Playgroud)
<input type="date" placeholder="Choose a Date" />
Run Code Online (Sandbox Code Playgroud)

  • 不幸的是,这似乎在Chrome中显示为"placeholdermm/dd/yyyy". (21认同)
  • 你只需要在:focus和:valid content属性之后添加`!important`,否则它会被覆盖.否则,好的黑客:) (3认同)
  • 不适用于我,Chrome 70-我仍然有这个:“ placeholdermm / dd / yyyy” (2认同)
  • 此解决方案无法在Ubuntu上的FireFox中使用。 (2认同)

Abd*_*ost 19

onfocus="(this.type='date')" onblur="(this.type='text')"
Run Code Online (Sandbox Code Playgroud)

  • 它可以工作,但您需要双击该字段才能查看日历。 (6认同)

Abd*_*ith 13

您可以在伪之前使用CSS.

.dateclass {
  width: 100%;
}

.dateclass.placeholderclass::before {
  width: 100%;
  content: attr(placeholder);
}

.dateclass.placeholderclass:hover::before {
  width: 0%;
  content: "";
}
Run Code Online (Sandbox Code Playgroud)
<input
  type="date"
  placeholder="Please specify a date"
  onClick="$(this).removeClass('placeholderclass')"
  class="dateclass placeholderclass">
Run Code Online (Sandbox Code Playgroud)

小提琴


小智 12

你可以这样做:

<input onfocus="(this.type='date')" class="js-form-control" placeholder="Enter Date">
Run Code Online (Sandbox Code Playgroud)


Xen*_*ogy 5

HTML5 日期输入字段实际上不支持占位符属性。浏览器总是会忽略它,至少按照当前规范是这样。

如此处所述


fel*_*osh 5

我使用这个 css 方法来模拟输入日期的占位符。

唯一需要js的是设置值的属性,如果使用React,它是开箱即用的。

input[type="date"] {
  position: relative;
}

input[type="date"]:before {
  content: attr(placeholder);
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  color: rgba(0, 0, 0, 0.65);
  pointer-events: none;
  line-height: 1.5;
  padding: 0 0.5rem;
}

input[type="date"]:focus:before,
input[type="date"]:not([value=""]):before
{
  display: none;
}
Run Code Online (Sandbox Code Playgroud)
<input type="date" placeholder="Choose date" value="" onChange="this.setAttribute('value', this.value)" />
Run Code Online (Sandbox Code Playgroud)