Skip to content

练习-酷炫的数字查找特效

assets/Numbercount.jpg

index.js

js
import "./views/event"

src/utils/isPrime.js

js
/**
 * 判断一个数字是否为质数:只能被1和自身整除的数
 * @param {number} n
 * @returns {boolean} 返回是否为质数
 */

function isPrime(n) {
  if (n < 2) {
    return false;
  }
  for (let i = 2; i <= n - 1; i++) {
    //发现,2到n-1之间,有一个数能整除n
    if (n % i === 0) {
      return false;
    }
  }
  return true;
}

export default isPrime;

src/utils/randomColor.js

js
const colors = [
  "#f26395",
  "#62efab",
  "#ef7658",
  "#ffe868",
  "#80e3f7",
  "#d781f9",
];

// 生成随机数
export function random(min, max) {
  return Math.floor(Math.random() * (max - min) + min);
}

/**生成随机颜色 */
function randomColor() {
  const index = random(0, colors.length);
  return colors[index];
}

export default randomColor;

src/views/pageUI.js

js
import isPrime from "../utils/isPrime";
import randomColor, { random } from "../utils/randomColor";

/* 页面对象 */
class UI {
  constructor(duration) {
    this.duration = duration; //动画间隔时长
    this.number = 1; //页面数据
    this.timer = null; //定时器id
    //页面的doms对象
    this.doms = {
      divContainer: document.querySelector("#divContainer"),
      divCenter: document.querySelector("#divCenter"),
    };
    // this.afterNumberCreated = null; //页面数据创建后回调函数,具体操作交给用户
  }

  /**开始 */
  start() {
    if (this.timer) return;
    this.timer = setInterval(() => {
      this.initDom();
      this.number++;
    }, this.duration);
  }

  /**暂停 */
  pause() {
    clearInterval(this.timer);
    this.timer = null;
  }

  /* 初始化页面 */
  initDom() {
    const span = document.createElement("span");
    span.innerText = this.number;
    if (isPrime(this.number)) {
      const color = randomColor();
      span.style.color = color;
      this.createPrimeOnCenter(this.number, color);
    }
    this.doms.divContainer.appendChild(span);

    this.addCenterNumber();
  }

  /* 添加中间数字 */
  addCenterNumber() {
    this.doms.divCenter.innerText = this.number;
  }

  /* 在中间产生一个质数 */
  createPrimeOnCenter(n, color) {
    const div = document.createElement("div");
    div.innerText = n;
    div.classList.add("center");
    div.style.color = color;
    document.querySelector("body").appendChild(div);
    // 动画
    getComputedStyle(div).width; //强制渲染,让div先出现在页面,要读取某个元素的位置或尺寸信息,则会导致浏览器重新渲染 reflow

    div.style.transform = `translate(${random(-200, 200)}px,${random(
      -200,
      200
    )}px)`;
    div.style.opacity = 0;
  }
}

export default UI;

src/views/event.js

js
import UI from "./pageUI";

//页面ui实例
const ui = new UI(100);
let isStart = false;

window.addEventListener("click", function () {
  if (isStart) {
    isStart = false;
    ui.pause();
  } else {
    isStart = true;
    ui.start();
  }
});

MIT License