利用Math对象的方法实现:Math.random() * 256可求出0~256(不包含256)之间的值,Math.floor()对值进行下取整
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#txt {
display: block;
width: 80px;
height: 30px;
background: rgb(10, 120, 0);
margin: 20px auto;
font-size: 20px;
text-align: center;
outline: none;
border: none;
cursor: pointer;
color: transparent;
text-shadow: 0 0 0 rgb(10, 10, 0);
}
</style>
</head>
<body>
<input type="text" id="txt">
<script>
//实现背景颜色变色的函数
function rgbBuild() {
//rgb值范围:0~255
//调用Math.random() * 256可求出0~256(不包含256)之间的值,
//再调用Math.floor()对值进行下取整
var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
//将随机获取的r,g,b值赋值给color
var color = "rgb(" + r + "," + g + "," + b + ")";
console.log(r, g, b);
//修改背景色样式
txt.style.background = color;
}
//实现数字字母随即组合的函数
function szBuild() {
//包含所有数字字母的字符串
var str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
var text = ''
//利用循环从str中截取5位随机的字符
for (var i = 0; i < 5; i++) {
var index = Math.floor(Math.random() * str.length);
text += str[index];
}
console.log(text);
txt.value = text;
}
//获取input对象
var txt = document.getElementById('txt');
//对input输入框添加点击功能
txt.onclick = function() {
//调用函数
rgbBuild();
szBuild();
}
</script>
</body>
</html>
实现的效果图如下所示:
注:每次点击input输入框,背景色和其内容随机变化