代码演练
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>脚本控制颜色</title>
<style>
.bg{
background-color: #000;
width: 300px;
height: 300px;
}
</style>
</head>
<body>
<div class="bg">
</div>
<button id="randomChange">随机颜色</button>
<button id="addChange">Hue色调递增</button>
<script src="js/jquery-3.3.1.js"></script>
<script>
$(function(){
var i=0;
$("#randomChange").click(function(){
var color= '#'+Math.floor(Math.random()*255).toString(10)
$(".bg").css("background-color",color)
});
$("#addChange").click(function(){
const color = `hsla(${i}, 50%, 50%, 1`
$(".bg").css("background-color",color)
i=i+10
});
});
</script>
</body>
</html>
代码修订
<script>
$(function(){
const hexString = "1000000";
const decNumber = parseInt(hexString, 16)
var i=0;
$("#randomChange").click(function(){
var color= '#'
var hexRandomString=Math.floor(Math.random()*decNumber).toString(16)
color=color+"0".repeat(6-hexRandomString.length)+hexRandomString;
console.log(color)
$(".bg").css("background-color",color)
});
$("#addChange").click(function(){
const color = `hsla(${i}, 50%, 50%, 1`
$(".bg").css("background-color",color)
i=i+10
if(i>360)
i=0;
});
});
</script>