如何使用输入或占位符名称复制到剪贴板? [英] how do i copy to clipboard with the input or placeholder name?

查看:304
本文介绍了如何使用输入或占位符名称复制到剪贴板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a simple form: https://jsfiddle.net/skootsa/8j0ycvsp/6/

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

我如何获得一个按钮,该按钮可以复制每个输入框的内容以及占位符"属性(或类名)?这样剪贴板结果如下所示:

How would I get a button that copied the contents of each input box + the "placeholder" attribute (or class name)? So that the clipboard results looked like this:

昵称:Johnnyboy

Nickname: Johnnyboy

年龄:22

推荐答案

您需要:

  1. 创建一个不可见的元素以复制数据
  2. 从表单中获取数据并将其设置为上一个元素
  3. 选择它
  4. 调用document.execCommand('copy')将所选文本复制到 剪贴板
  1. create an invisible element to copy the data
  2. get the data from your form and set it to the previous element
  3. select it
  4. call document.execCommand('copy') to copy the selected text to the clipboard

我已经更新了您的小提琴,请查看 https://jsfiddle.net/8j0ycvsp/9/

I have updated your fiddle, check it out 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');
    }
}

这篇关于如何使用输入或占位符名称复制到剪贴板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆