如何制作随机数生成器并将其复制到剪贴板

时间:2018-03-23 23:44:17

标签: javascript html css

我还不是一个程序员,但我真的想制作一个使用Javascript随机选择字符的文本框,然后将这些字符输出到HTML文本字段中,边上有一个按钮来复制字符那个文本字段。 Here is a picture of what I am looking for

我在互联网上发现了几个代码片段,但我不确定如何将它们放在一起。如果你能帮助我,我会非常感激!

如果你只是路过,我希望你度过美好的一天!

HTML

<input type="text" value="Hello World" id="myInput">
<button onclick="myFunction()">Copy text</button>

CSS

.tooltip {
  position: relative;
  display: inline-block;
}

    .tooltip .tooltiptext {
      visibility: hidden;
      width: 140px;
      background-color: #555;
      color: #fff;
      text-align: center;
      border-radius: 6px;
      padding: 5px;
      position: absolute;
      z-index: 1;
      bottom: 150%;
      left: 50%;
      margin-left: -75px;
      opacity: 0;
      transition: opacity 0.3s;
    }

    .tooltip .tooltiptext::after {
      content: "";
      position: absolute;
      top: 100%;
      left: 50%;
      margin-left: -5px;
      border-width: 5px;
      border-style: solid;
      border-color: #555 transparent transparent transparent;
    }

    .tooltip:hover .tooltiptext {
      visibility: visible;
      opacity: 1;
    }

JAVASCRIPT(用于“复制到剪贴板”按钮)

function myFunction() {
  var copyText = document.getElementById("myInput");

  copyText.select();

  document.execCommand("Copy");

  alert("Copied the text: " + copyText.value);
}

JAVASCRIPT(对于随机字符生成器) (现在它只在控制台日志中显示它)

var randomString = function(length) {
    var text = "";
    var possible = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890!?";
    for(var i = 0; i < length; i++) {
        text += possible.charAt(Math.floor(Math.random() * possible.length));
    }
    return text;
}

var rs = randomString(10);

console.log("Our Random String Is: " + rs);

1 个答案:

答案 0 :(得分:0)

创建一个copyText函数,您可以将生成的字符串发送到:

const input = document.querySelector('input');
function copyText(text) {
  input.value = text;
  input.select();
  document.execCommand("Copy");
  console.log("Copied");
}

const randomString = function(length) {
  let text = "";
  const possible = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890!?";
  for(let i = 0; i < length; i++) {
    text += possible.charAt(Math.floor(Math.random() * possible.length));
  }
  return text;
}

input.addEventListener('click', () => {
  const rs = randomString(10);
  copyText(rs);
});
<input>

(由于浏览器安全性,您必须单击事件的输入)