批改状态:未批改
老师批语:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>随机颜色</title>
<style type="text/css">
*{margin:0;padding: 0}
div{
width:1000px;
height:800px;
margin:50px auto;
}
</style>
<script type="text/javascript" src="static/js/jquery.js"></script>
</head>
<body>
<div class="box">
<button onclick="bg_color()">生成随机背景颜色</button>
</div>
<script>
function bg_color(){
var bg='#';
r=Math.floor(Math.random()*16).toString(16)+Math.floor(Math.random()*16).toString(16);
g=Math.floor(Math.random()*16).toString(16)+Math.floor(Math.random()*16).toString(16);
b=Math.floor(Math.random()*16).toString(16)+Math.floor(Math.random()*16).toString(16);
bg+=r+g+b;
console.log(bg);
document.getElementsByClassName('box')[0].style.background=bg;
}
</script>
</body>
</html>点击 "运行实例" 按钮查看在线实例
心得:
toString()要生成十六进制时,要在里面加参数16
另有通过做好一个包含十六进制数的数组,生成随机的数组下标,循环组合出颜色值
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号