javascript生成指定位數隨機數程式碼例項

antzone發表於2017-04-12

本章節分享一段例項,它實現了生成指定位數隨機數效果。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
.wrap {
  width: 1000px;
  margin: 30px auto;
}
.d1 {
  width: 300px;
  height: 200px;
  margin: 50px auto;
  background: #333;
  font: 50px/200px Arial;
  color: #fff;
  text-align: center;
  border-radius: 10px;
}
</style>
<script>
function a() {
  var d1 = document.getElementById('d1');
  var oA = parseInt(Math.random() * (999 - 100 + 1) + 100, 10);
  d1.innerHTML = oA;
};
function b() {
  var d1 = document.getElementById('d1');
  var oB = parseInt(Math.random() * (9999 - 1000 + 1) + 1000, 10);
  d1.innerHTML = oB;
};
function c() {
  var d1 = document.getElementById('d1');
  var oC = parseInt(Math.random() * (99999 - 10000 + 1) + 10000, 10);
  d1.innerHTML = oC;
};
function d() {
  var d1 = document.getElementById('d1');
  var oD = parseInt(Math.random() * (999999 - 100000 + 1) + 100000, 10);
  d1.innerHTML = oD;
};
</script>
</head>
<body>
<div class="wrap">
  <button id="f4" onclick="a()">隨機三位數</button>
  <button id="f6" onclick="b()">隨機四位數</button>
  <button id="f6" onclick="c()">隨機五位數</button>
  <button id="f6" onclick="d()">隨機六位數</button>
  <div class="d1" id="d1">1</div>
</div>
</body>
</html>

相關文章