【问题标题】:Hidden Input field when created on the fly, isn't much useful for temporary storing strings动态创建时隐藏的输入字段,对于临时存储字符串没有多大用处
【发布时间】:2020-07-19 00:00:17
【问题描述】:

我正在制作一个密码创建脚本,我不想在其中显示生成的密码,而只是将生成的密码复制到剪贴板。

我有实现上述功能的脚本如下:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <button type="button" onclick="alert(generatePassword())">Generate Password</button>
        <script type="application/x-javascript">
        function generatePassword() {
            var length = 15,
                charset1 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
                charset2 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@#$%^&",
                charset3 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@#$%^&*()!+=~",
                retVal = "";
            for (var i = 0, n = charset3.length; i < length; ++i) {
                retVal += charset3.charAt(Math.floor(Math.random() * n));
            }
            copyToClipboard2(retVal);
            return 'Password ready to be pasted';
        }
        const copyToClipboard2 = str => {
            const el1 = document.createElement('input');
            el1.setAttribute('type','text');
            // el1.setAttribute('type','hidden');
            el1.value = str;
            document.body.appendChild(el1);
            el1.select();
            document.execCommand('copy');
            document.body.removeChild(el1);
        };
        </script>
    </body>
</html>

注意注释掉的行,我已经注释了它,因为它不起作用。

所以正如我已经提到的问题,我如何利用即时创建的hiddeninput字段在复制到剪贴板之前临时存储密码,代码与上面相同?

【问题讨论】:

  • 您对文本元素所做的事情(有些人使用 textarea 代替)似乎还不错。隐藏字段不是文本字段,因此无法使用select()“选择”其内容,这就是您无法将其复制到剪贴板的原因。

标签: javascript html dom-events copy-paste hidden-field


【解决方案1】:

我不确定这是否重复,因为这是一个更具体的问题,但How do I copy to the clipboard in JavaScript? 有多种复制到剪贴板的解决方案,包括execCommand 方法。

向下滚动到复杂示例:复制到剪贴板而不显示输入,这建议将输入或文本区域固定在左上角,基本上没有高度、宽度、边框等,以便它是不可见。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-02
    • 2017-06-09
    • 1970-01-01
    • 1970-01-01
    • 2020-04-23
    • 2021-09-21
    相关资源
    最近更新 更多