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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18146350/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 11:59:23  来源:igfitidea点击:

How do I simulate placeholder functionality on input date field?

html

提问by Shkarik

It's impossible to use placeholder on date fields but I really need it.

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

I want two date inputs with texts "From" and "To" on each one as placeholders.

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

回答by Roman

I'm using the following CSS only trick:

我只使用以下 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" />

回答by Abdo-Host

use this input attribute events

使用此输入属性事件

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>

回答by Abdullah Gheith

You can use CSS's before pseudo.

您可以在伪之前使用 CSS。

.dateclass {
  width: 100%;
}

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

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

FIDDLE

小提琴

回答by Oday Hazeem

You can do something like this:

你可以这样做:

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

回答by Xenology

The HTML5 date input field actually does not support the attribute for placeholder. It will always be ignored by the browser, at least as per the current spec.

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

As noted here

正如这里所指出的

回答by Jeff Noel

The input[type="date"]DOMElement only takes the following value: YYYY-MM-DD, any other format or text with be skipped.

input[type="date"]一个DOMElement只需要以下值:YYYY-MM-DD,任何其他格式或文本与被跳过。

Live Demo

现场演示

HTML

HTML

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

Pure JavaScript

纯 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

绩效考核

In this exact case, with 2 inputelements, Pure JavaScript is ~40% ± 10% faster.

在这种确切的情况下,使用 2 个input元素,纯 JavaScript快约 40% ± 10%

With 32 inputelements, the difference remains the same (~43% ± 10% faster for Pure JS).

对于 32 个input元素,差异保持不变(对于 Pure JS,速度提高了约 43% ± 10%)。

回答by felixmosh

I'm using this css method in order to simulate placeholder on the input date.

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

The only thing that need js is to setAttribute of the value, if using React, it works out of the box.

唯一需要 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;
}
<input type="date" placeholder="Choose date" value="" onChange="this.setAttribute('value', this.value)" />

回答by Guillaume Gendre

As mentionned here, I've made it work with some ":before" pseudo-class and a small bit of javascript. Here is the idea :

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

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

Then in javascript, add the "not_empty" class depending on the value in the onChange and onKeyUp events.

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

You can even add all of this dynamically on every date fields. Check my answer on the other thread for the code.

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

It's not perfect but it's working well in Chrome and iOS7 webviews. Maybe it could help you.

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

回答by sidarcy

As i mentioned here

正如我在这里提到的

initially set the field type to text.

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

on focus change it to type date

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

回答by Coop

Try this:

尝试这个:

Add a placeholder attribute to your field with the value you want, then add this jQuery:

使用您想要的值将占位符属性添加到您的字段,然后添加以下 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')); }
  });

I've not tested it for fields that can't take placeholders but you shouldn't need to change anything in the code at all.

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

On another note, this code is also a great solution for browsers that don't support the placeholder attribute.

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