基於JavaScript實現隨機點名器

本文實例為大傢分享瞭JavaScript實現隨機點名器的具體代碼,供大傢參考,具體內容如下

HTML代碼:

<body>
 <h1>點名啦</h1>
 <div id="did">
  <input id="rollcall-id" type="button" value="隨機點名器"><br>
  <input id="action-id" type="submit" onclick="doClick()" value="開始">
 </div>
</body>

CSS代碼:

<style>
 * {
  margin: 0px;
  padding: 0px;
 }

 body {
  background-color: rgb(255, 249, 249);
 }

 h1 {
  text-align: center;
  padding-top: 100px;
  color: rgba(250, 54, 129, 0.562);
 }

 #did {
  position: relative;
  width: 200px;
  margin: 60px auto;
 }

 #did input:first-child {
  width: 200px;
  height: 60px;
  background-color: rgba(250, 54, 129, 0.562);
  /* 不要邊框或設邊框為透明 */
  border: none;
  border-radius: 20px;
  font-size: 25px;
  color: #fff;
  box-shadow: 0px 0px 3px 3px rgba(250, 54, 129, 0.158);
  /* 點擊時邊框消失 */
  outline: 0;
 }

 #did input:nth-last-child(1) {
  width: 100px;
  height: 40px;
  margin: 40px 50px;
  background-color: rgba(250, 54, 129, 0.562);
  border: 1px solid transparent;
  background-color: rgba(255, 68, 177, 0.432);
  border-radius: 15px;
  box-shadow: 0px 0px 2px 2px rgba(250, 54, 129, 0.158);
  font-size: 17px;
  color: #333;
  outline: 0;
  transition: color 0.2s ease-out;
  transition: box-shadow 0.2s ease-out;
 }

 #did input:nth-last-child(1):hover {
  color: #fff;
  cursor: pointer;
  box-shadow: 0px 0px 4px 4px rgba(250, 54, 129, 0.158);
 }
</style>

JavaScript代碼:

<script>
 var rollcall = document.getElementById("rollcall-id");
 var action = document.getElementById("action-id");
 var h1 = document.getElementsByTagName("h1");

 //不能用name,用name隻會取得一個字符
 var allName = ["張柳菲", "高穎影", "趙溫言", "李穎", "鄧辰希", "莫若鄰", "秦橙",
  "吳筱宇", "趙希", "馬素瀅", "呂沁雅", "羅鴻哲", "夏素蕓", "謝焱之",
  "曹夢朦", "李允書", "周楓橋", "孫浩", "江雁菁", "楊振凱", "林舒言",
  "錢妙妙", "郭景", "杜貝貝", "童閔然", "鐘小凌", "韓雲韻", "白然之"];

 //隨機產生一個名字
 function stringRandom() {
  return parseInt(Math.random() * allName.length);
 }

 var time = null;
 var luckName;
 //開始
 function doStart() {
  if (time == null) {
   time = setInterval(function () {
    //獲取隨機點名的值
    luckName = allName[stringRandom()];
    rollcall.setAttribute("value", luckName);
   }, 100);
  }
 }

 //停止
 function doStop() {
  if (time != null) {
   clearInterval(time);
   time = null;
  }
 }

 //點擊事件
 function doClick() {
  if (action.value == "開始") {
   //改變樣式
   action.style.backgroundColor = "#cecece";
   action.style.boxShadow = "0px 0px 2px 2px rgba(100, 100, 100, 0.4)";
   action.value = "停止";
   h1[0].innerHTML = "點名啦";

   //開始隨機點名
   doStart();
  } else if (action.value == "停止") {
   action.style.backgroundColor = "rgba(255, 68, 177, 0.432)";
   action.style.boxShadow = "0px 0px 2px 2px rgba(250, 54, 129, 0.158)";
   action.value = "開始";
   h1[0].innerHTML = "恭喜" + luckName + "同學獲得一次發言機會";

   //停止
   doStop();
  }
 }
</script>

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: