如何使用输入或占位符名称复制到剪贴板?

how do i copy to clipboard with the input or placeholder name?

我有一个简单的表格:https://jsfiddle.net/skootsa/8j0ycvsp/6/

<div class='field'>
<input placeholder='Nickname' type='text'>
</div>
<div class='field'>
<input placeholder='Age' type='text'>
</div>

如何获得复制每个输入框内容的按钮 + "placeholder" 属性(或 class 名称)?这样剪贴板结果看起来像这样:

Nickname: Johnnyboy

Age: 22

那就试试吧

var input = document.querySelectorAll('.field input');

document.getElementById('submit').addEventListener('click', function () {
 var innerHTMLText = "";
 for (var i = 0; i < input.length; i++) {
  innerHTMLText += input[i].placeholder + ':' + input[i].value + '      ';
 }
 console.log(innerHTMLText);
 document.getElementsByClassName('bix')[0].innerHTML = innerHTMLText;
});

您需要:

  1. 创建一个不可见的元素来复制数据
  2. 从您的表单中获取数据并将其设置为前一个元素
  3. select这
  4. 调用 document.execCommand('copy') 将 selected 文本复制到 剪贴板

我已经更新了你的fiddle,请查看https://jsfiddle.net/8j0ycvsp/9/

如果您需要代码

function copyToClipboard() {

    /*get inputs from form */
    var inputs = document.querySelectorAll("#the-form input[type=text]");

    /*do a copy of placeholder and contents*/
    var clipboardText = ''
    for (var i = 0, input; input = inputs[i++];) {
        clipboardText += input.placeholder+': '+(input.value ? input.value : '' )+'\n';     
    }

    /*create hidden textarea with the content and select it*/
    var clipboard = document.createElement("textarea");
    clipboard.style.height = 0;
    clipboard.style.width  = 0;
    clipboard.value = clipboardText;
    document.body.appendChild(clipboard);
    clipboard.select();

    console.log(clipboard.value);

    /*do a copy fren*/
    try {
        if(document.execCommand('copy'))
            console.log('Much succes, wow!');
        else 
            console.log('Very fail, wow!');

    } catch (err) {        
        console.log('Heckin concern, unable to copy');
    }
}