简体   繁体   English

是否有JavaScript方法可让html日期输入显示日期选择器?

[英]Is there a JavaScript method to make a html date input display the datepicker?

I would like to trigger the display of a date input's date-picker from an external button. 我想从外部按钮触发日期输入的日期选择器的显示。

<input id="date" type="date" />
<button>display date</button>

For instance if I had the above code, how would I show the date-picker (the box which appears and allows you to pick a date) by clicking the button? 例如,如果我有上面的代码,如何单击按钮显示日期选择器(出现的框,允许您选择日期)? I do not want to use jQuery or other libraries. 我不想使用jQuery或其他库。 Is there a way to show the native date-picker from an external trigger with vanilla JavaScript? 有没有办法显示来自使用香草JavaScript的外部触发器的本机日期选择器?

I'm looking for something like this: 我正在寻找这样的东西:

var button = document.querySelector("button");
button.onclick = () => {
    var input = document.querySelector("#date");
    input.showDatePicker();
}

You can with 你可以

let x = document.getElementById('myDate'),
  d = new Date(),
  m = d.getMonth() < 10 ? `0${d.getMonth()}` : `${d.getMonth()}`,
  day = d.getDay() < 10 ? `0${d.getDay()}` : `${d.getDay()}`;

x.value = d.getFullYear() + "-" + m + "-" + day;

Demo 演示

This works well on firefox and edge : 这在firefox和edge上效果很好:

 <input id="date" type="date" /> <button>display date</button> <script type="text/javascript"> var button = document.querySelector("button"); button.onclick = () => { var input = document.querySelector("#date"); input.focus() input.click() } </script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM