每次做项目都是red,pink,blue,不仅单调乏味,而且充分暴露了自己三级甲等的英语水平,作为一名有理想,积极向上的程序员,这是果断不能忍的事情,今天刚好写一个用原生js给特定元素随机添加背景色的方法,瞬间让单调的生活丰富多彩起来,有了此方法妈妈再也不用担心我找不到女朋友了。
源码:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
<style type="text/css">
.box{
height: 200px;
width: 200px;
background: red;
}
</style>
</head>
<body>
<div class="box"></div>
<button class="btn">点我随机变化颜色</button>
<script type="text/javascript">
var btn = document.querySelector(".btn");
var box = document.querySelector(".box");
btn.onclick = function () {
randColor(box)
}
function randColor(element) { //随机改变背景色
var ranColor = '#' + ('00000' + (Math.random() * 0x1000000 << 0).toString(16)).slice(-6);
element.style.background = ranColor;
}
</script>
</body>
</html>