<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
</head>
<style type="text/css">
article{
display: flex;
flex-wrap: wrap;
font-size: 12px;
color:wheat;
}
.color-item{
width:10%;
min-height: 40px;
margin: 1%;
}
#message{
position: absolute;top:5%;left:40%;
display: none; font-size: 0.8rem;
width:20%;line-height: 30px;
min-height: 30px;
border:1px solid #918c97;
border-radius: 5px;text-align: center;
}
</style>
<body>
<h2>点击自动复制颜色<h2>
<span id="message">复制成功</span>
<article >
</article>
</body>
<script type="text/javascript">
for(var i=0;i<50;i++){
var bg = getRandomColor();
var htm = "<div class='color-item' id='item-"+i+"' style='background:"+bg+"'> "+bg+"</div>";
document.getElementsByTagName('article')[0].innerHTML += htm;
}
var colors = document.getElementsByClassName('color-item');
for(var i=0;i<colors.length;i++){
colors[i].addEventListener('click',copyText,false)
}
var timeHandle;
function copyText(ev)
{
let range = document.createRange()
range.selectNodeContents(ev.target)
let selection = window.getSelection()
selection.removeAllRanges()
selection.addRange(range)
document.execCommand('copy')
selection.removeAllRanges()
document.getElementById('message').style.display = 'inline-block'
clearInterval(timeHandle)
timeHandle = setInterval(function(){
document.getElementById('message').style.display = 'none'
},1000)
}
function getRandomColor(){
return "#"+
(function(color){
var rand = Math.floor(Math.random()*0XFFFFFF).toString(16);
return rand.length == 6 ? rand : arguments.callee(color);
})('')
}
</script>
</html>
生成随机颜色,并点击复制