<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>随机红包</title>
<style>
#con {
width: 300px;
height: 300px;
border: 1px dotted green;
}
</style>
</head>
<body>
<input type="text" id="money" name="money" />元
<br>
<input type="text" id="num" name="num" />个
<br>
<input type="button" value="点击" id="btn" name="btn" />
<p>注意:该随机红包只产生整数红包!</p>
<h3>红包的个数和每个红包的money:</h3>
<div id="con"></div>
<script>
//1.定义变量
var oBtn = document.getElementById('btn');
var oCon = document.getElementById('con');
var oMoney = document.getElementById('money');
var oNum = document.getElementById('num');
//2.按钮点击事件
oBtn.onclick = function () {
//将 con内容清空
oCon.innerHTML = '';
//获取钱数和红包个数
var money = oMoney.value;
var num = oNum.value;
var nn = 0;//红包默认的钱数
var sum = num - 1;
for (var i = 0; i < sum; i++) {
//取一个红包的钱数
nn = Math.ceil(getRandom(0, money / 2));
//在总钱数里将这个红包的钱数减去
money = money - nn;
oCon.innerHTML += '<div>' + nn + '</div>';
}
oCon.innerHTML += '<div>' + money + '</div>';
}
//随机数的函数
function getRandom(one, two) {
return Math.random() * (two - one) + one;
}
</script>
</body>
</html>