【问题标题】:How do I simulate placeholder functionality on input date field?如何在输入日期字段上模拟占位符功能?
【发布时间】:2013-08-11 08:46:33
【问题描述】:

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

我想要两个日期输入,每个都带有文本“From”和“To”作为占位符。

【问题讨论】:

  • 设置消失onfocus并重新出现onblur的广告默认值?
  • 当您在不兼容的浏览器中模拟占位符行为时,请注意这将如何影响您的验证。
  • From 和 To 是 <label>s,而不是 placeholders。

标签: html


【解决方案1】:

我正在使用以下 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: "";
  }
<input type="date" placeholder="Choose a Date" />

【讨论】:

  • 不幸的是,这似乎在 Chrome 中显示为“placeholdermm/dd/yyyy”。
  • 是的。仅适用于 iOS 和 Android 上的 Chrome。这是一个黑客:)
  • margin-right: 0.5em; 添加到第一个声明中,以便在占位符和输入之间创建一个很好的分隔。您还可以将第一行更改为:content: attr(placeholder)':';,以便在占位符和输入之间添加一个冒号。
  • 您只需要在 :focus 和 :valid 内容属性之后添加 !important ,否则它会被覆盖。否则,不错的 hack :)
  • 不适合我,Chrome 70 - 我还有这个:“placeholdermm/dd/yyyy”
【解决方案2】:

使用这个输入属性事件

onfocus="(this.type='date')" onblur="(this.type='text')"

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<div class="container mt-3">
  <label for="date">Date : </label>
  <input placeholder="Your Date" class="form-control" type="text" onfocus="(this.type='date')" onblur="(this.type='text')" id="date">
</div>

【讨论】:

  • 可以,但是需要双击字段才能看到日历。
  • 这在 ios 14 中不起作用 - 它会弹出键盘而不是日期选择器,但输入会变成日期字段,因此您看不到正在输入的文本。
  • 你是怎么让双击消失的? @帕特森
【解决方案3】:

您可以在伪之前使用 CSS。

.dateclass {
  width: 100%;
}

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

.dateclass.placeholderclass:hover::before {
  width: 0%;
  content: "";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<input
  type="date"
  placeholder="Please specify a date"
  onClick="$(this).removeClass('placeholderclass')"
  class="dateclass placeholderclass">

FIDDLE

【讨论】:

  • 像其他类似的答案一样,在 Firefox 中不起作用。
【解决方案4】:

你可以这样做:

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

【讨论】:

    【解决方案5】:

    HTML5 日期输入字段实际上不支持占位符的属性。浏览器将始终忽略它,至少按照当前规范。

    As noted here

    【讨论】:

      【解决方案6】:

      我正在使用这个 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;
      }
      &lt;input type="date" placeholder="Choose date" value="" onChange="this.setAttribute('value', this.value)" /&gt;

      【讨论】:

      • 这个实际上适用于 IO(Chrome、Firefox 等),而大多数其他选项都不能。
      【解决方案7】:

      input[type="date"] DOMElement 仅采用以下值:YYYY-MM-DD,任何其他格式或文本都将被跳过。

      Live Demo

      HTML

      <input type="text" placeholder="bingo" />
      <input type="date" placeholder="2013-01-25" />
      

      纯 JavaScript

      window.onload = function () {
          /* Grab all elements with a placeholder attribute */
          var element = document.querySelectorAll('[placeholder]');
      
          /* Loop through each found elements */
          for (var i in element) {
              /* If the element is a DOMElement and has the nodeName "INPUT" */
              if (element[i].nodeType == 1 && element[i].nodeName == "INPUT") {
      
                  /* We change the value of the element to its placeholder attr value */
                  element[i].value = element[i].getAttribute('placeholder');
                  /* We change its color to a light gray */
                  element[i].style.color = "#777";
      
                  /* When the input is selected/clicked on */
                  element[i].onfocus = function (event) {
                      /* If the value within it is the placeholder, we clear it */
                      if (this.value == this.getAttribute('placeholder')) {
                          this.value = "";
                          /* Setting default text color */
                          this.style.color = "#000";
                      };
                  };
      
                  /* We the input is left */
                  element[i].onblur = function (event) {
                      /* If the field is empty, we set its value to the placeholder */
                      if (this.value == "") {
                          this.value = this.getAttribute('placeholder');
                          this.style.color = "#777";
                      }
                  };
              }
          }
      }
      

      Performance review

      在这个确切的情况下,有 2 个 input 元素,纯 JavaScript 是 ~40% ± 10% faster

      使用 32 个 input 元素,差异保持不变(Pure JS 快了约 43% ± 10%)。

      【讨论】:

        【解决方案8】:

        得到了解决这个问题最简单的方法——在你的 HTML 输入标签中使用这个语法

              <input type="text" id="my_element_id" placeholder="select a date" name="my_element_name" onfocus="(this.type='date')" />
              </div>
        

        【讨论】:

          【解决方案9】:

          试试这个:

          用你想要的值向你的字段添加一个占位符属性,然后添加这个 jQuery:

          $('[placeholder]').each(function(){
              $(this).val($(this).attr('placeholder'));
            }).focus(function(){
              if ($(this).val() == $(this).attr('placeholder')) { $(this).val(''); }
            }).blur(function(){
              if ($(this).val() == '') { $(this).val($(this).attr('placeholder')); }
            });
          

          我没有针对不能使用占位符的字段进行测试,但您根本不需要更改代码中的任何内容。

          另一方面,对于不支持占位符属性的浏览器,此代码也是一个很好的解决方案。

          【讨论】:

            【解决方案10】:

            正如提到的here,我已经使它与一些“:before”伪类和一小部分javascript一起工作。 这是想法:

             #myInput:before{ content:"Date of birth"; width:100%; color:#AAA; } 
             #myInput:focus:before,
             #myInput.not_empty:before{ content:none }
            

            然后在 javascript 中,根据 onChange 和 onKeyUp 事件中的值添加“not_empty”类。

            您甚至可以在每个日期字段上动态添加所有这些内容。检查我在另一个线程上的答案以获取代码。

            它并不完美,但在 Chrome 和 iOS7 webviews 中运行良好。也许它可以帮助你。

            【讨论】:

              【解决方案11】:

              正如我提到的here

              最初将字段类型设置为文本。

              在焦点上将其更改为键入日期

              【讨论】:

                【解决方案12】:

                好的,这就是我所做的:

                $(document).on('change','#birthday',function(){
                    if($('#birthday').val()!==''){
                        $('#birthday').addClass('hasValue');
                    }else{
                        $('#birthday').removeClass('hasValue');
                    }
                })
                

                这是在给定值时删除占位符。

                input[type="date"]:before {
                  content: attr(placeholder) !important;
                  color: #5C5C5C;
                  margin-right: 0.5em;
                }
                input[type="date"]:focus:before,
                input[type="date"].hasValue:before {
                  content: "" !important;
                  margin-right: 0;
                }
                

                在焦点或 .hasValue 时,删除占位符及其边距。

                【讨论】:

                  【解决方案13】:

                  使用 jQuery(确保您可以使用 Vanilla 实现这一点。这确保日期格式仍然相同。

                  $(function() {
                    $('.sdate').on('focus', function() {
                      $(this).attr('type', 'date');
                    });
                    $('.sdate').on('blur', function() {
                      if(!$(this).val()) { // important
                        $(this).attr('type', 'text');
                      }
                    });
                  });
                  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
                  
                  <input type="text" class="sdate" placeholder="From">

                  【讨论】:

                  • 并非所有浏览器都支持此功能
                  【解决方案14】:

                  CSS

                  input[type="date"] {position: relative;}
                  input[type="date"]:before {
                  	position: absolute;left: 0px;top: 0px;
                  	content: "Enter DOB";
                  	color: #999;
                  	width: 100%;line-height: 32px;
                  }
                  input[type="date"]:valid:before {display: none;}
                  &lt;input type="date" required /&gt;

                  【讨论】:

                    猜你喜欢
                    • 2013-12-17
                    • 2019-11-22
                    • 2018-10-14
                    • 2012-03-26
                    • 2013-04-08
                    • 1970-01-01
                    • 2014-10-13
                    • 1970-01-01
                    • 2012-09-04
                    相关资源
                    最近更新 更多