一个冒泡排序的动画

闲着无聊突然~

<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>

就是如此了~

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,684评论 25 709
  • 首先用未做过任何加密的登录作为案例: 本例中用到了layui,下载地址: 点我下载 教程文档: 文档地址 当然这...
    前端丶米店阅读 2,458评论 0 1
  • Gradle是一个自动化构建工具(build system),构建能做的事很多,除了包括包依赖管理(depende...
    一川烟草i蓑衣阅读 394评论 0 1
  • 亲爱的简书,这是和你的初次相遇,请多关照。希望我能和你做个挚友,能与你倾心相交。在这里我想给自己一片真诚而自...
    苏梦63059阅读 137评论 0 0
  • 父→子 传送子组件的属性是父组件传递的,动态修改父组件的值,子组件也会对应的变化 子→父父组件将自身方法作为pr...
    cilec阅读 337评论 0 0