未显示输入类型的占位符="日期"领域

时间:2013-12-02 05:02:23

标签: html5 cordova datepicker placeholder

我正在做一个phonegap应用程序,当我尝试type="date"输入字段时,如下所示,它显示iPhone中的日期选择器,正如我所料,但它没有显示我给出的占位符。我在SO中发现了同样的问题,但在任何地方都没有解决方案,希望有人可以帮助我。感谢。

 <input placeholder="Date" class="textbox-n" type="date" id="date">

32 个答案:

答案 0 :(得分:117)

这可能不合适......但它终于帮助了我。

<input placeholder="Date" class="textbox-n" type="text" onfocus="(this.type='date')"  id="date"> 

答案 1 :(得分:69)

如果您使用mvp的方法但添加onblur事件以将其更改回文本字段,以便在输入字段失去焦点时再次显示占位符文本。它只是让黑客变得更好。

<input placeholder="Date" class="textbox-n" type="text" onfocus="(this.type='date')" onblur="(this.type='text')" id="date">

希望这有帮助。

答案 2 :(得分:28)

我最终使用了以下内容。

关于Firefox评论:通常,Firefox不会为输入类型日期显示任何文本占位符。 但由于这是一个Cordova / PhoneGap问题,因此不应该担心(除非你想针对FirefoxOS开发)。

&#13;
&#13;
input[type="date"]:not(.has-value):before{
  color: lightgray;
  content: attr(placeholder);
}
&#13;
<input type="date" placeholder="MY PLACEHOLDER" onchange="this.className=(this.value!=''?'has-value':'')">
&#13;
&#13;
&#13;

答案 3 :(得分:20)

我在我的css中使用了这个:

input[type="date"]:before{
    color:lightgray;
    content:attr(placeholder);
}

input[type="date"].full:before {
    color:black;
    content:""!important;
}

并将这样的somenthing放入javascript:

$("#myel").on("input",function(){
    if($(this).val().length>0){
    $(this).addClass("full");
}
else{
   $(this).removeClass("full");
   }
 });

它适用于移动设备(Ios8和Android)。但我使用jquery输入掩码用于桌面输入文本类型。如果您的代码在ie8上运行,这个解决方案是一个不错的方法。

答案 4 :(得分:14)

截至今天(2016年),我已经成功使用了这2个片段(加上它们与Bootstrap4配合使用)。

左侧输入数据,左侧占位符

input[type="date"]:before {
  color: lightgrey;
  content: attr(placeholder) !important;
  margin-right: 0.5em;
}
input[type="date"]:focus:before {
  content: '' !important;
}
单击时,

占位符消失
exports.up = function(knex, Promise) {
  return removeForeignKeyChecks()
    .then(createMemberTable)
    .then(createAddressTable)
    .then(addForeignKeyChecks);

  function removeForeignKeyChecks() {
    return knex.raw('SET foreign_key_checks = 0;');
  }

  function addForeignKeyChecks() {
    return knex.raw('SET foreign_key_checks = 1;');
  }

  function createMemberTable() {
    return knex.schema.createTable('Member', function (table) {
      table.bigIncrements('id').primary().unsigned();
      table.string('email',50);
      table.string('password');

      /* CREATE FKS */
      table.bigInteger('ReferralId').unsigned().index();
      table.bigInteger('AddressId').unsigned().index().inTable('Address').references('id');
    });
  }

  function createAddressTable() {
    return knex.schema.createTable('Address', function (table) {
      table.bigIncrements('id').primary().unsigned();
      table.index(['city','state','zip']);

      table.string('city',50).notNullable();
      table.string('state',2).notNullable();
      table.integer('zip',5).unsigned().notNullable();
    });
  }
};

答案 5 :(得分:9)

根据the HTML standard

  

不得指定以下内容属性,并且不适用于该元素:accept,alt,checked,dirname,formaction,formenctype,formmethod,formnovalidate,formtarget,height,inputmode,maxlength,minlength,multiple,pattern,< strong>占位符,大​​小,src和宽度。

答案 6 :(得分:9)

我在jQuery中使用它: http://jsfiddle.net/daviderussoabram/65w1qhLz/

$('input[type="date"], input[type="datetime"], input[type="datetime-local"], input[type="month"], input[type="time"], input[type="week"]').each(function() {
    var el = this, type = $(el).attr('type');
    if ($(el).val() == '') $(el).attr('type', 'text');
    $(el).focus(function() {
        $(el).attr('type', type);
        el.click();
    });
    $(el).blur(function() {
        if ($(el).val() == '') $(el).attr('type', 'text');
    });
});

答案 7 :(得分:7)

它对我有用:

input[type='date']:after {
  content: attr(placeholder)
}

答案 8 :(得分:4)

找到了解决问题的更好方法。 我认为这会对您有所帮助。聚焦后,该框会将类型更改为文本,以便显示占位符。重点关注时,其类型会更改为日期,以便显示日历视图。

<input placeholder="Date" class="textbox-n" type="text" onfocusin="(this.type='date')" onfocusout="(this.type='text')"  id="date"> 

答案 9 :(得分:3)

在当前正确答案中解决问题&#34;点击该字段会显示屏幕键盘而不是日期选择器&#34;:

问题是由浏览器在单击(=文本)时根据输入类型进行操作引起的。因此,有必要停止聚焦输入元素(模糊),然后以编程方式重新启动焦点,在第一步中由JS定义为type = date的输入元素。键盘以phonenumber模式显示。

<input placeholder="Date" type="text" onfocus="this.type='date';
                      this.setAttribute('onfocus','');this.blur();this.focus();">

答案 10 :(得分:2)

我花了一段时间搞清楚这一点,将其保留为type="text",然后添加onfocus="(this.type='date')",如上图所示。

我甚至喜欢上面提到的onBlur想法

<input placeholder="Date" class="textbox-n" type="text" onfocus="(this.type='date')" onblur="(this.type='text')" id="date">

希望这可以帮助那些没有完全了解上述内容的人

答案 11 :(得分:2)

你可以

  1. 将其设置为文字类型
  2. 转换为焦点日期
  3. 点击它
  4. ...让用户查看日期
  5. on change存储值
  6. 设置输入以输入文字
  7. 将文本类型输入值设置为存储值
  8. 像这样......

    &#13;
    &#13;
    $("#dateplaceholder").change(function(evt) {
      var date = new Date($("#dateplaceholder").val());
      $("#dateplaceholder").attr("type", "text");
      $("#dateplaceholder").val(date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getFullYear());
    });
    $("#dateplaceholder").focus(function(evt) {
      $("#dateplaceholder").attr("type", "date");
      setTimeout('$("#dateplaceholder").click();', 500);
    });
    $("#dateplaceholder").attr("type", "text");
    &#13;
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
    <input type="date" id="dateplaceholder" placeholder="Set the date" />
    &#13;
    &#13;
    &#13;

答案 12 :(得分:2)

我使用离子框架和@Mumthezir提供的解决方案几乎是完美的。如果有人和我有同样的问题(更改后,输入仍然是焦点,滚动时,值只是消失)所以我添加了onchange来生成input.blur()

<input placeholder="Date" class="textbox-n" type="text" onfocus=" (this.type='date')" onchange="this.blur();"  id="date"> 

答案 13 :(得分:2)

所以我决定最终做的就是在这里,它在包括iPhone和机器人在内的所有移动浏览器上都能正常工作。

$(document).ready(function(){

  $('input[type="date"]').each(function(e) {
    var $el = $(this), 
        $this_placeholder = $(this).closest('label').find('.custom-placeholder');
    $el.on('change',function(){
      if($el.val()){
        $this_placeholder.text('');
      }else {
        $this_placeholder.text($el.attr('placeholder'));
      }
    });
  });
  
});
label {
  position: relative;  
}
.custom-placeholder {
    #font > .proxima-nova-light(26px,40px);
    position: absolute;
    top: 0;
    left: 0;
    z-index: 10;
    color: #999;
}
<label>
  <input type="date" placeholder="Date">
  <span class="custom-placeholder">Date</span>
</label>

                                 日期             

答案 14 :(得分:2)

总结日期输入问题:

  • 您必须显示它们(即避免显示:无)否则将不会触发输入UI;
  • 占位符与它们相矛盾(根据规范,因为它们必须显示特定的UI);
  • 将它们转换为另一种输入类型以进行无焦点时间确实允许占位符,但焦点会触发错误的输入UI(键盘),至少在一小段时间内,因为焦点事件无法取消。
  • 插入(之前)或添加(之后)内容并不会阻止显示日期输入值。

我发现满足这些要求的解决方案是使用常用技巧来设置原生表单元素的样式:确保元素显示但不可见,通过其关联标签显示其预期样式。通常,标签将显示为输入(包括占位符),但在其上方。

所以,HTML就像:

<div class="date-input>
  <input id="myInput" type="date"> 
  <label for="myInput"> 
    <span class="place-holder">Enter a date</span> 
  </label>
</div>

可以设为:

.date-input {
  display: inline-block;
  position: relative;
}
/* Fields overriding */
input[type=date] + label {
  position: absolute;  /* Same origin as the input, to display over it */
  background: white;   /* Opaque background to hide the input behind */
  left: 0;             /* Start at same x coordinate */
}

/* Common input styling */
input[type=date], label {  
  /* Must share same size to display properly (focus, etc.) */
  width: 15em;
  height: 1em;
  font-size: 1em;
}

此类关联标签上的任何事件(点击,焦点)都会反映在字段本身上,因此会触发日期输入界面。

如果您想要实时测试此解决方案,可以从平板电脑或手机运行this Angular version

答案 15 :(得分:1)

我采用了jbarlow的想法,但是我在onblur函数中添加了一个if,因此只有在该值为空的情况下字段才更改其类型

<input placeholder="Date" class="textbox-n" type="text" onfocus="(this.type='date')" onblur="(this.value == '' ? this.type='text' : this.type='date')" id="date">

答案 16 :(得分:1)

我很惊讶只有一个答案与我使用的类似。
我从@Dtipson对@Mumthezir VP的回答的评论中得到了启发。

为此,我使用了两个输入,一个是带有animal.name的伪输入,我在其中设置了占位符,另一个是带有animal.name的实数字段。
在其容器上的type="text"事件上,我隐藏了伪输入并显示了真实的输入,而在type="date"事件上则执行了相反的操作。显然,如果设置了值,我将保留真实输入。
我编写了使用纯Javascript的代码,但是如果您使用jQuery(我愿意),则很容易对其进行“转换”。

mouseenter
mouseleave
// "isMobile" function taken from this reply:
// https://stackoverflow.com/a/20293441/3514976
function isMobile() {
  try { document.createEvent("TouchEvent"); return true; }
  catch(e) { return false; }
}

var deviceIsMobile = isMobile();

function mouseEnterListener(event) {
  var realDate = this.querySelector('.real-date');
  // if it has a value it's already visible.
  if(!realDate.value) {
    this.querySelector('.fake-date').style.display = 'none';
    realDate.style.display = 'block';
  }
}

function mouseLeaveListener(event) {
  var realDate = this.querySelector('.real-date');
  // hide it if it doesn't have focus (except
  // on mobile devices) and has no value.
  if((deviceIsMobile || document.activeElement !== realDate) && !realDate.value) {
    realDate.style.display = 'none';
    this.querySelector('.fake-date').style.display = 'block';
  }
}

function fakeFieldActionListener(event) {
  event.preventDefault();
  this.parentElement.dispatchEvent(new Event('mouseenter'));
  var realDate = this.parentElement.querySelector('.real-date');
  // to open the datepicker on mobile devices
  // I need to focus and then click on the field.
  realDate.focus();
  realDate.click();
}

var containers = document.getElementsByClassName('date-container');
for(var i = 0; i < containers.length; ++i) {
  var container = containers[i];
  
  container.addEventListener('mouseenter', mouseEnterListener);
  container.addEventListener('mouseleave', mouseLeaveListener);
  
  var fakeDate = container.querySelector('.fake-date');
  // for mobile devices, clicking (tapping)
  // on the fake input must show the real one.
  fakeDate.addEventListener('click', fakeFieldActionListener);
  // let's also listen to the "focus" event
  // in case it's selected using a keyboard.
  fakeDate.addEventListener('focus', fakeFieldActionListener);
  
  var realDate = container.querySelector('.real-date');
  // trigger the "mouseleave" event on the
  // container when the value changes.
  realDate.addEventListener('change', function() {
    container.dispatchEvent(new Event('mouseleave'));
  });
  // also trigger the "mouseleave" event on
  // the container when the input loses focus.
  realDate.addEventListener('blur', function() {
    container.dispatchEvent(new Event('mouseleave'));
  });
}

我也在Android手机上对此进行了测试,并且可以正常工作,当用户点击该字段时,显示日期选择器。唯一的事情是,如果实际输入没有任何值,并且用户在不选择日期的情况下关闭了日期选择器,则输入将保持可见,直到他们轻按它之外。没有事件可听,以了解日期选择器何时关闭,所以我不知道如何解决。

我没有要在其上进行测试的iOS设备。

答案 17 :(得分:1)

尝试我的解决方案。我使用'required'属性来了解输入是否已填充,如果不是,则显示属性'placeholder'的文本

//HTML
<input required placeholder="Date" class="textbox-n" type="date" id="date">

//CSS
input[type="date"]:not(:valid):before {
   content: attr(placeholder);
   // style it like it real placeholder
}

答案 18 :(得分:1)

<input placeholder="01-01-2021" class="textbox-n" type="text" onfocus="(this.type='date')" onblur="(this.type='text')" id="date" />

答案 19 :(得分:1)

找到一种更好的方法来处理用户基本理解,使用鼠标悬停并在点击时打开datepicker:

<input type="text" onfocus="(this.type='date')" onmouseover="(this.type = 'date')" onblur="(this.value ? this.type = 'date' : this.type = 'text')" id="date_start" placeholder="Date">

同时隐藏webkit箭头并使其100%宽以覆盖点击:

input[type="date"] {
    position: relative;
}
input[type="date"]::-webkit-calendar-picker-indicator {
  position: absolute;
  height: 100%;
  width: 100%;
  opacity: 0;
  left: 0;
  right: 0;
  top:0;
  bottom: 0;
}

答案 20 :(得分:1)

从Angular的角度来看,我设法将一个占位符放在输入类型的日期元素中。

首先我定义了以下css:

.placeholder {
    color: $text-grey;
  }

  input[type='date']::before {
    content: attr(placeholder);
  }

  input::-webkit-input-placeholder {
    color: $text-grey;
  }

这是必要的原因是,如果css3内容的颜色与普通占位符不同,那么我不得不使用一个普通的占位符。

<input #birthDate
         class="birthDate placeholder"
         type="date"
         formControlName="birthDate"
         placeholder="{{getBirthDatePlaceholder() | translate}}"
         [class.error]="!onboardingForm.controls.birthDate.valid && onboardingForm.controls.birthDate.dirty"
         autocomplete="off"
         >

然后在模板中使用了viewchild birthDate属性,以便能够从组件中访问此输入。并在占位符属性上定义了一个角度表达式,它将决定是否显示占位符。这是解决方案的主要缺点,就是您必须管理占位符的可见性。

@ViewChild('birthDate') birthDate;

getBirthDatePlaceholder() {
  if (!this.birthDate) {
    return;
  } else {
    return this.birthDate.nativeElement.value === '' ?
    'ONBOARDING_FORM_COMPONENT.HINT_BIRTH_DATE' :
    '';
  }
}

答案 21 :(得分:0)

如果您只关心移动设备:

input[type="date"]:invalid:before{
    color: rgb(117, 117, 117);
    content: attr(placeholder);
}

答案 22 :(得分:0)

&#13;
&#13;
<input placeholder="Date" type="text" onMouseOver="(this.type='date')" onMouseOut="(this.type='text')"  id="date" class="form-control">
&#13;
&#13;
&#13;

mumthezir的修订代码

答案 23 :(得分:0)

HTML:

<div>
    <input class="ui-btn ui-btn-icon-right ui-corner-all ui-icon-calendar ui-shadow" id="inputDate" type="date"/>
    <h3 id="placeholder-inputDate">Date Text</h3>
</div>

JavaScript:

$('#inputDate').ready(function () {
$('#placeholder-inputDate').attr('style'
    , 'top: ' + ($('#placeholder-inputDate').parent().position().top + 10)
    + 'px; left: ' + ($('#placeholder-inputDate').parent().position().left + 0) + 'px; position: absolute;');
$('#inputDate').attr('style'
    , 'width: ' + ($('#placeholder-inputDate').width() + 32) + 'px;');
});

答案 24 :(得分:0)

这是另一个不使用js且仍使用CSS content的可能的黑客。请注意,由于某些浏览器不支持:after进行输入,因此我们需要以其他方式选择输入,与content attr('')

相同

input[type=date]:invalid+span:after {
  content:"Birthday";
  position:absolute;
  left:0;
  top:0;
}

input[type=date]:focus:invalid+span:after {
  display:none;
}

input:not(:focus):invalid {
  color:transparent;
}

label.wrapper {
	position:relative;
}
<label class="wrapper">
	<input
 	  type="date"
  	  required="required" 
	/>
	<span></span>
</label>

答案 25 :(得分:0)

这对我有用,使用它作为输入元素:

<input name="birthdate" class="" class="wpcf7-form-control wpcf7-date 
 wpcf7-validates-as-required wpcf7-validates-as-date birthdate" value="" 
 aria-required="true" aria-invalid="false" placeholder="birthdate *" 
 type="date">

此CSS显示了一个永久占位符。所选值显示在占位符之后。

input[type="date"]:before {
    content: attr(placeholder) !important;
    margin-right: 0.5em;
    display: block;
}
/* only for FF */
@-moz-document url-prefix() {
    input[type="date"]:before {
        content: attr(placeholder) !important;
        margin-right: 0.5em;
        display: block;
        position: absolute;
        left: 200px; /* please adopt */
    }
}

我将此解决方案用于带有contact-form-7插件的Wordpress表单。

答案 26 :(得分:0)

我都无法在iOS 12的Chrome上正常使用这些解决方案,并且大多数解决方案都不适合页面上可能存在的多个日期输入。我执行了以下操作,该操作基本上会在输入的日期上创建一个假标签,并在点击时将其删除。如果视口宽度超过992px,我还将删除虚假标签。

JS:

function addMobileDatePlaceholder() {
    if (window.matchMedia("(min-width: 992px)").matches) {
        $('input[type="date"]').next("span.date-label").remove();
        return false;
    }

    $('input[type="date"]').after('<span class="date-label" />');

    $('span.date-label').each(function() {
        var $placeholderText = $(this).prev('input[type="date"]').attr('placeholder');
        $(this).text($placeholderText);
    });

    $('input[type="date"]').on("click", function() {
        $(this).next("span.date-label").remove();
    });
}

CSS:

@media (max-width: 991px) {
    input[type="date"] {
        padding-left: calc(50% - 45px);
    }

    span.date-label {
        pointer-events: none;
        position: absolute;
        top: 2px;
        left: 50%;
        transform: translateX(-50%);
        text-align: center;
        height: 27px;
        width: 70%;
        padding-top: 5px;
    }
}

答案 27 :(得分:0)

嘿所以昨晚我遇到了同样的问题,想出了你所有答案的组合,一些闪亮的魔法做得很好:

HTML:

<input type="date"  name="flb5" placeholder="Datum"     class="datePickerPlaceHolder"/>

CSS:

@media(max-width: 1024px) {
   input.datePickerPlaceHolder:before {
      color: #A5A5A5; //here you have to match the placeholder color of other inputs
      content: attr(placeholder) !important;
   }
}

jQuery:

$(document).ready(function() {
    $('input[type="date"]').change(function(){
            if($(this).val().length < 1) {
                $(this).addClass('datePickerPlaceHolder');
            } else {
                $(this).removeClass('datePickerPlaceHolder');
            }
    });
});

说明: 那么,这里发生了什么,首先在 HTML 中,这是非常直接的,只需做一个基本的HMTL5-date-input并设置一个占位符。 下一站: CSS ,我们设置一个:before-pseudo-element伪造我们的占位符,它只是从输入本身获取占位符的属性。我只能从1024px的视口宽度下来这个 - 为什么我稍后会告诉你。 现在 jQuery ,经过几次重构后,我想出了一些代码,它会检查每一个变化是否有值设置,如果没有它(重新)添加类,反之亦然。

知道问题:

  • Chrome的默认日期选择器存在问题,这就是媒体查询的用途。它将添加默认'dd.mm.yyyy'事物的占位符前面。你也可以把日期输入的占位符设置为'date:'并调整输入中没有值的颜色...对我来说这导致了一些其他较小的问题,所以我只是没有在'更大的显示它'屏幕
希望有所帮助! cheerio!

答案 28 :(得分:0)

在考虑到不引人注目的javascript的情况下扩展@ mvp的解决方案,这是方法:

HTML:

<input type="text" placeholder="Date" class="js-text-date-toggle">

使用Javascript:

$('.js-text-date-toggle').on('focus', function() {
  $(this).attr('type', 'date') }
).on('blur', function() {
  $(this).attr('type'), 'text') }
)

答案 29 :(得分:0)

这在某些情况下可能会有所帮助。

<input type="text" id="date" onclick="this.type='date'" onblur="this.type='text'" placeholder="Date" class="textbox-n" name="myDate" />
      

答案 30 :(得分:-1)

扩展Mumthezir的版本在iOS上运行得更好,基于Mathijs Segers的评论:

(使用一些AngularJS,但希望你能得到这个想法。)

<label style='position:relative'>
    <input type="date" 
           name="dateField" 
           onfocus="(this.type='date')"
           ng-focus="dateFocus=true" ng-blur="dateFocus=false" />
    <span ng-if='!dateFocus && !form.date' class='date-placeholder'>
        Enter date
    </span>
</label>

因为它全部包含在label中,所以点击span会自动关注input

CSS:

.date-placeholder {
    display: inline-block;
    position: absolute;
    text-align: left;
    color: #aaa;
    background-color: white;
    cursor: text;
    /* Customize this stuff based on your styles */
    top: 4px;
    left: 4px;
    right: 4px;
    bottom: 4px;
    line-height: 32px;
    padding-left: 12px;
}

答案 31 :(得分:-3)

您可以使用“value”属性,例如:

<input type="date" value="Date" class="textbox-n" id="date"/>