在 html5 日期字段上启用复制/粘贴

Kar*_*yan 7 html javascript

能够从文本框中复制值并粘贴到我的 html5 表单中的另一个文本框中。同样的方式我如何从日期字段复制值。

<input type="date" />

我想从一个日期字段复制值并将其粘贴到另一个日期字段。

Red*_*Red 6

是本土的吗?

不,日期input字段的行为与文本input字段不同。

解决方法

我曾经遇到过同样的问题并创建了一个解决方法。

当您dlbclick输入字段时,它会暂时将自身更改为text输入字段并自动选择其值。CTRL所以你可以使用+复制日期C

当您想要将日期从文本字段复制到日期输入字段时,它也适用。

注册一个focusout事件以将输入重置为其原始状态type="date"

// get all date input fields
let dateInputs = document.querySelectorAll('[type="date"]');

dateInputs.forEach(el => {
    // register double click event to change date input to text input and select the value
    el.addEventListener('dblclick', () => {
        el.type = "text";
        
        // After changing input type with JS .select() wont work as usual
        // Needs timeout fn() to make it work
        setTimeout(() => {
          el.select();
        })
    });
    
    // register the focusout event to reset the input back to a date input field
    el.addEventListener('focusout', () => {
        el.type = "date";
    });
});
Run Code Online (Sandbox Code Playgroud)
input {
  display: block;
  width: 150px;
}
Run Code Online (Sandbox Code Playgroud)
<label>Double click me</label>
<input type="date" value="2011-09-29" />
<input type="date" placeholder="paste the date here" />
Run Code Online (Sandbox Code Playgroud)