两个div方块第一个是用来显示16进制颜色值的,第二个就是随机颜色的方块,
点击第二个方块的时候,第一个div里面会显示这个16进制的颜色值
题主要的代码如下,有帮助麻烦点个采纳【本回答右上角】,谢谢~~有其他问题可以继续交流~
<!doctype html>
<style>
#div1,#div2{float:left;width:80px;height:80px;border:solid 1px #999;margin-right:20px;font-size:12px;text-align:center;line-height:80px}
</style>
<div id="div1"></div>
<div id="div2"></div>
<input type="button" value="切换颜色" onclick="rndColor()"/>
<script>
var div1 = document.getElementById('div1'), div2 = document.getElementById('div2'), color;
function addZero(v) { if (v.length < 2) return '0' + v; return v;}
function rndColor() {
div1.innerHTML = '';
div2.style.backgroundColor = color = '#'
+ addZero(Math.floor(Math.random() * 256).toString(16))
+ addZero(Math.floor(Math.random() * 256).toString(16))
+ addZero(Math.floor(Math.random() * 256).toString(16));
}
div2.onclick = function () { div1.innerHTML = color }
rndColor()
</script>
随机的颜色值放在一个变量里 显示的方块的div绑定存放颜色值的变量
原生js的话 随机出来的颜色值 获取到节点 innerHTML = 颜色值