首页 > 解决方案 > 我应该使用什么类型的函数来复制随机生成的十六进制值?

问题描述

我正在尝试对copyHexValue按钮应用一个函数,以将生成的十六进制值复制到用户的剪贴板。关于我应该在函数中包含哪些代码的任何建议?

function genNewColor() {
  var symbols, color;
  symbols = "0123456789ABCDEF";

  color = "#";
  for (var i = 0; i < 6; i++) {
    color = color + symbols[Math.floor(Math.random() * 16)]
  }
  document.body.style.background = color;
  document.getElementById("hex").innerHTML = color
}
body {
  margin: 0;
  padding: 0;
  background: #161818;
  font-family: "Consolas";
}

.color {
  margin-top: 300px;
  text-align: center;
}

#hex {
  display: block;
  color: white;
  font-size: 100px;
  text-transform: uppercase;
  margin: 0px;
}

.color button {
  background: none;
  outline: 10px;
  color: white;
  cursor: pointer;
  font-size: 40px;
  border: 3px solid white;
}
<!DOCTYPE html>
<html>

<head>
  <title>
    Color Generator
  </title>
</head>

<body>

  <div class="color">
    <span id="hex">#??????</span>
    <button onclick="genNewColor()">Generate new random color</button>
    <button onclick="copyHexValue()">Copy hex value</button>
  </div>

</body>

</html>

标签: javascripthtmlcss

解决方案


这就是你想要的。您可以阅读更多关于在 w3 学校复制到剪贴板的信息 -在这里

只需运行代码片段即可查看它的实际效果。

function genNewColor() {
  var symbols, color;
  symbols = "0123456789ABCDEF";

  color = "#";
  for (var i = 0; i < 6; i++) {
    color = color + symbols[Math.floor(Math.random() * 16)]
  }
  document.body.style.background = color;
  document.getElementById("hex").innerHTML = color
}

function copyHexValue() {
  var copyHex = document.createElement('input');
   copyHex.value = document.getElementById("hex").innerHTML;
   document.body.appendChild(copyHex);
   copyHex.select();
   document.execCommand('copy');
   alert('Copied '+copyHex.value)
   console.log('Copied '+copyHex.value)
   document.body.removeChild(copyHex);    
}
body {
  margin: 0;
  padding: 0;
  background: #161818;
  font-family: "Consolas";
}

.color {
  margin-top: 300px;
  text-align: center;
}

#hex {
  display: block;
  color: white;
  font-size: 100px;
  text-transform: uppercase;
  margin: 0px;
}

.color button {
  background: none;
  outline: 10px;
  color: white;
  cursor: pointer;
  font-size: 40px;
  border: 3px solid white;
}
<!DOCTYPE html>
<html>

<head>
  <title>
    Color Generator
  </title>
</head>

<body>

  <div class="color">
    <span id="hex">#??????</span>
    <button onclick="genNewColor()">Generate new random color</button>
    <button onclick="copyHexValue()">Copy hex value</button>
  </div>

</body>

</html>


推荐阅读