原生js实现三个卡位随机显示图片

可以应用于游戏机或卜卦中

如果需要降低某种结果的概率,请自行添加算法处理。本例仅作简单的随机处理。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <img id="img1" style="display: inline-block;" src="https://www.baidu.com/img/flexible/logo/pc/result.png" width="150" height="45">&nbsp;&nbsp;
  <img id="img2" style="display: inline-block;" src="https://www.baidu.com/img/flexible/logo/pc/result.png" width="150" height="45">&nbsp;&nbsp;
  <img id="img3" style="display: inline-block;" src="https://www.baidu.com/img/flexible/logo/pc/result.png" width="150" height="45">
  <!-- 这里图片的路径src, 自己找一张图,写上自己的路径就好了 -->
  <p>
  <button id="btn">停止或启动</button>
  </p>
  <script>
    var timer = null;//全局命名定时器的名字
    var img1,img2,img3,src1,src2,rand1,rand2,rand3;
    window.onload = function () {
      img1 = document.getElementById('img1');
      img2 = document.getElementById('img2');
      img3 = document.getElementById('img3');
      src1 = 'https://www.baidu.com/img/flexible/logo/pc/result.png';
      src2 = 'https://p.ssl.qhimg.com/t012cdb572f41b93733.png';
    };
    var flag = false;//全局声明状态切换的初始值
    btn.onclick = function () {
      if (flag) {
        clearInterval(timer);
        console.log('src1:'+rand1);
        console.log('src2:'+rand2);
        console.log('src3:'+rand3);
        console.log('定时器已停止');
        flag = false;
      } else if (flag == false) {
        console.log('定时器启动');
        timer = setInterval(() => {
            rand1 = Math.round(Math.random()*1);
            rand2 = Math.round(Math.random()*1);
            rand3 = Math.round(Math.random()*1);
            if(rand1) img1.src = src1;
            else img1.src = src2;
            if(rand2) img2.src = src1;
            else img2.src = src2;
            if(rand3) img3.src = src1;
            else img3.src = src2;
        }, 100);
        flag = true;
      }
    }
  </script>
</body>
</html>