一個冒泡排序的動畫

閑著無聊突然~

<template>
  <div class="container">
  </div>
</template>
<style>
.container {
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.container  .sort {
  height: 50px;
  width: 50px;
  border: 1px solid #ccc;
  transition: 1s;
  line-height: 50px;
  text-align: center;
  position: absolute;
}
</style>

模板與css搭建完成

<script>
  init() {
    const arr = [5, 4, 8, 9, 6, 5, 4, 12, 3, 6, 7, 8, 56];
    const container = document.querySelector('.container');
    const fragment = document.createDocumentFragment();
    const len = arr.length;
    arr.forEach((val, index) => {
      const temp = document.createElement('div');
      temp.className = 'sort';
      temp.style.left = index * 60 + 'px';
      temp.id = index;
      temp.innerHTML = val;
      fragment.append(temp);
    });
    container.append(fragment);

    let time = 1; // 排序動畫時間
    for (let i = 0; i < len; i++) {
      for (let j = i + 1; j < arr.length; j++) {
        if (arr[i] > arr[j]) {
          let temp = arr[i];
          arr[i] = arr[j];
          arr[j] = temp;
          setTimeout(() => {
            const x = document.getElementById(j);
            const y = document.getElementById(i);
            [x.style.left, y.style.left] = [y.style.left, x.style.left];
            [x.id, y.id] = [y.id, x.id];
          }, time * 1000);
          time++
        }
      }
    }
  }
  init()
</script>

就是如此了~

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,217評論 25 708
  • 首先用未做過任何加密的登錄作為案例: 本例中用到了layui,下載地址: 點我下載 教程文檔: 文檔地址 當(dāng)然這...
    前端丶米店閱讀 2,550評論 0 1
  • Gradle是一個自動化構(gòu)建工具(build system),構(gòu)建能做的事很多,除了包括包依賴管理(depende...
    一川煙草i蓑衣閱讀 466評論 0 1
  • 親愛的簡書,這是和你的初次相遇,請多關(guān)照。希望我能和你做個摯友,能與你傾心相交。在這里我想給自己一片真誠而自...
    蘇夢63059閱讀 147評論 0 0
  • 父→子 傳送子組件的屬性是父組件傳遞的,動態(tài)修改父組件的值,子組件也會對應(yīng)的變化 子→父父組件將自身方法作為pr...
    cilec閱讀 362評論 0 0

友情鏈接更多精彩內(nèi)容