Loading

你来比划我来猜,打乱词语web实现

需求:

老婆需要一个能打乱词语的软件。应用于一些活动?类似 你来比划我来猜【词语】

具体需求:

  1. 上传一个txt文件(文件中有N条预置词语)
  2. 将文件中的词语顺序打乱
  3. 展示打乱后的一个词语
  4. 切换下一个词语

由于没有什么软件展示需求,就用最简单的web来实现了下

项目地址:

项目地址

示例文件

这是示例文件链接(请另存为 txt 格式)

代码如下


<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>随机词语</title>
    <style>
      body {
        height: 100vh;
        margin: 0;
        padding: 0;
      }
      .p {
        padding: 5px;
      }
      .show {
        padding: 40px;
        text-align: center;
        font-size: 60px;
      }
    </style>
  </head>
  <body>
    <div class="p">
      <button id="upload">上传文件</button>
    </div>
    <div class="p">
      <button id="randarr">打乱顺序(重置)</button>
    </div>
    <!-- <div class="p">
      <button id="start">开始(下一个)</button>
    </div> -->

    <div class="show" id="show"></div>

    <script>
      const randarr = document.getElementById("randarr");
      const upload = document.getElementById("upload");
      // const start = document.getElementById("start");
      const show = document.getElementById("show");

      let arr = [];
      let index = 0;
      upload.onclick = function (e) {
        const ele = document.createElement("input");
        ele.type = "file";
        ele.accept = "text/plain";
        ele.onchange = async () => {
          const file = ele.files[0];
          var reader = new FileReader();
          reader.readAsText(file, "utf8"); 
          reader.onload = function () {
            // this 指代filereader
            arr = this.result.split("\n");
            console.log(arr); // 文本内容
            index = 0;
            show.innerText = "";
          };
        };
        ele.click();
        e.stopPropagation();
      };

      randarr.onclick = function (e) {
        randomArr(arr);
        index = 0;
        show.innerText = "";
        e.stopPropagation();
      };

      document.body.onclick = function () {
        if (index < arr.length) {
          show.innerText = arr[index];
          index++;
        } else {
          show.innerText = "没有了!";
        }
      };

      function randomArr(a) {
        a.sort(randomSort);
        function randomSort(a, b) {
          return Math.random() > 0.5 ? -1 : 1;
        }
        return a;
      }
    </script>
  </body>
</html>

posted @ 2022-07-27 15:46  ZJH_BLOGS  阅读(105)  评论(0编辑  收藏  举报