javascript - 如果没有创建选择,如何复制日期类型的输入?

标签 javascript jquery

我有一个简单的输入:

<input type="date" class="self-select" value="1980-05-04">
<input type="text" class="self-select" value="my birthday">

我有一个监听所有这些输入的:

$(document).on('focus', '.self-select', function(){
    $(this).select();
});

这个想法是,当用户点击输入字段时,它的内容被选中,所以他只需要 ctrl+c 来复制。

但这不适用于 Chrome 中的 type="date"。没有选择,基本上没有办法从输入字段复制日期值。

这是 fiddle : https://fiddle.jshell.net/Dmatafonov/s8r9dt6j/

最佳答案

我设法写了一些“hacky”四处走动......

技巧是在 CTRL+C keydown 上将日期输入类型临时设置为“文本”时复制到剪贴板 ( using this other great SO answer )...

它并不完美,因为焦点上只选择了日期的一部分......
有些用户会挠头,直到他们注意到整个日期都被复制了。
我对此没有解决方案。

enter image description here

重要的是复制到剪贴板是有效的。
试试这个片段!

// Your on focus -> select event handler
$(document).on('focus', '.self-select', function(){
    $(this).select();
});



// An on keydown event handler to copy to clipboard when [ctrl]+[C] is pressed
// Exclusively for the "date" inputs.
$(document).on('keydown', 'input[type="date"]', function(e){

    if( e.which == 67 && e.ctrlKey ){
        var copiedDate = $(this).val();
        //console.log( copiedDate );

        // First, get the value and fix the date format from YYYY-MM-DD to MM/DD/YYYY

        var tempDate = copiedDate.split("-");
        var year = tempDate.shift();
        //console.log( year );
        tempDate.push(year);
        var fixedDate = tempDate.join("/");
        console.log( fixedDate );

        // Then temporarly change the input type from "date" to "text"

        $(this).attr("type","text").val(fixedDate);


        // Use the copy to clipboard function
        $(this).select();
        copyToClipboard($(this));

        // Set the input type back to "date" a small delay later
        var that=$(this);
        setTimeout(function(){
            that.attr("type","date").val(copiedDate);  // And restore original value
        },20)
    }
});

// ---------------------------------
// A nice JavaScript "copy to clipboard" function found here : https://stackoverflow.com/a/22581382/2159528
// ---------------------------------

function copyToClipboard(elem) {
    // create hidden text element, if it doesn't already exist
    var targetId = "_hiddenCopyText_";
    var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA";
    var origSelectionStart, origSelectionEnd;
    if (isInput) {
        // can just use the original source element for the selection and copy
        target = elem;
        origSelectionStart = elem.selectionStart;
        origSelectionEnd = elem.selectionEnd;
    } else {
        // must use a temporary form element for the selection and copy
        target = document.getElementById(targetId);
        if (!target) {
            var target = document.createElement("textarea");
            target.style.position = "absolute";
            target.style.left = "-9999px";
            target.style.top = "0";
            target.id = targetId;
            document.body.appendChild(target);
        }
        target.textContent = elem.textContent;
    }
    // select the content
    var currentFocus = document.activeElement;
    //target.focus();
    target.setSelectionRange(0, target.value.length);

    // copy the selection
    var succeed;
    try {
        succeed = document.execCommand("copy");
    } catch(e) {
        succeed = false;
    }
    // restore original focus
    if (currentFocus && typeof currentFocus.focus === "function") {
        currentFocus.focus();
    }

    if (isInput) {
        // restore prior selection
        elem.setSelectionRange(origSelectionStart, origSelectionEnd);
    } else {
        // clear temporary content
        target.textContent = "";
    }
    return succeed;
}
/* Textarea sizing for this snippet */
#pasteIt{
    width:316px;
    height:150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="date" class="self-select" value="1980-05-04">
<input type="text" class="self-select" value="my birthday">
<br>
<br>
<textarea id="pasteIt" placeholder="Paste here to test your clipboard."></textarea>

关于javascript - 如果没有创建选择,如何复制日期类型的输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41189150/

相关文章:

Javascript RegExp - 它包括空格和括号

php - 获取youtube视频文件的时间长度

javascript - 需要使用 mootools 来编写简单的脚本而不是 jquery...怎么样?

javascript - div#d1 切换到 p#1 点击 - 如何?

jquery - 需要以数组或字符串的形式获取 div 中的所有跨度值?

javascript - Safari 8 和 7.1 中的地理定位 API 不断请求许可

javascript - 单击时输出字段和按钮消失

javascript - Node.js 中的异步查询是否有助于克服实时数据流中的延迟?

jquery - Reload $(document).ready(function() ajax页面重新加载后

javascript - 这个漂亮的小 jQuery 代码似乎不起作用.. 任何人都知道为什么?