<!DOCTYPE html>
<html>
<head>
<title>改变颜色</title>
<meta charset="utf-8">
<style type="text/css">
#bordercolor{
width: 400px;
height: 400px;
margin: 0 auto;
}
</style>
</head>
<body>
<div id="bordercolor"></div>
<div style="margin: 20px auto;width: 150px">
<input type="button" name="" value="+" onclick="add(1);">
<input type="button" name="" value="开始" onclick="begin();">
<input type="button" name="" value="-" onclick="add(0);">
</div>
<script type="text/javascript">
/*
//随机颜色
function randomHexColor() { //随机生成十六进制颜色
var hex = Math.floor(Math.random() * 16777216).toString(16); //生成ffffff以内16进制数
while (hex.length < 6) { //while循环判断hex位数,少于6位前面加0凑够6位
hex = '0' + hex;
}
return '#' + hex; //返回‘#'开头16进制颜色
}
*/
var tar;//定义一个全局的变量
var speed = 1000;
//改变颜色的函数
function changeColor(){
document.getElementById("bordercolor").style.backgroundColor = randomColor();
}
//随机颜色的函数
function randomColor(){
var arr = [0,1,2,3,4,5,6,7,8,9,"A","B","C","D","E","F"];
var restcolor = "#";
for(var i = 0; i < 6; i++){
restcolor = restcolor + arr[Math.floor(Math.random() * 16)];
}
return restcolor;
}
//开始的按键
function begin(){
tar = setInterval(changeColor,speed);
}
//加减的按键
function add(player){
if (player == 1) {
clearInterval(tar);
speed = speed + 1000;
tar = setInterval(changeColor,speed);
}else if (player == 0) {
clearInterval(tar);
speed = speed - 1000;
tar = setInterval(changeColor,speed);
}
}
</script>
</body>
</html>
关于延时函数的简单应用--随机颜色不同速度切换
最新推荐文章于 2024-05-02 00:30:00 发布
