javascript - js给dom元素一一添加多个class

标签 javascript html css

我想用一个事件监听器向我的 div 添加 2 个类,但我希望它添加一个列表,更新 DOM,然后添加第二个类

当用户单击 1 键时,我需要将 ID 为 app 的 div 移动到顶部,然后向左移动,但它同时向上和向左移动。

<!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>
    <style>
      body {
        height: 100%;
        width: 100%;
        background-image: url("TPHRG floorplan1.png");
        background-repeat: no-repeat;
        background-attachment: fixed;
        /* background-position: center; */
        background-size: 980px 400px, cover;
      }

      .robot_start_top {
        top: 280px;
        transition: top 1s;
      }

      .robot_start_left {
        position: fixed;
        left: 600px;
        transition: all 1s;
      }

      .robot_end_left {
        left: 500px;
      }

      .robot_end_top {
        top: 180px;
      }

      .robot1_start_left {
        position: fixed;
        left: 600px;
        transition: left 1s;
      }

      .robot1_end_left {
        left: 400px;
      }
    </style>
  </head>
  <body onkeydown="move(event)">
    <div class="robot_start_left robot_start_top" id="app">
      <img id="robot" style="width:30px; height:40px" />
    </div>

    <script>
      let count = 0;
      var move = function(event) {
        if (event.keyCode === 97) {
          const appDiv = document.getElementById("app");
          setTimeout(function() {
            appDiv.classList.add("robot_end_top");
          }, 0);
          setTimeout(function() {
            appDiv.classList.add("robot_end_left");
          }, 0);
        }

        if (event.keyCode === 98) {
          const appDiv = document.getElementById("app");
          appDiv.classList.add("robot1_end_left");
        }
      };
    </script>
  </body>
</html>

但是通过这种方式,它一次添加了所有 2 个类。

这是 CodeSandBox中的全部代码

最佳答案

浏览器通常会让像您这样的 JavaScript 代码执行大量 DOM 更新,而无需执行任何视觉操作。他们会等到脚本退出(如事件处理程序)或直到脚本中的某些内容要求浏览器在提供答案之前进行视觉更新。

在您的情况下,最简单的做法是将“第二”类的添加推迟几分之一秒;具体多长时间取决于您希望它看起来像什么。你这样做的方式就像是

  setTimeout(() => { appDiv.classList.add("robot_end_left") }, 500);

那个 500 表示在添加第二个类之前等待 500 毫秒。

关于javascript - js给dom元素一一添加多个class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59381391/

相关文章:

html - 输入边框在 Chrome 中显示,但在 IE 中不显示

javascript - 自动嵌入Youtube的jQuery函数需要接受多种链接格式

javascript - 如何在 React.js 中使用 jQuery 依赖节点模块?

html - 如何提供独立于文件类型的缩略图形式的文档预览

css - 如何使用 CSS 选择没有 "type"的 &lt;input&gt;

javascript - 使用 Javascript 和 CSS 进行多页打印

html - 我们可以用 css 改变 ListBox 吗?

css - Compass 多次创建相同的 Sprite 贴图

javascript - 笛卡尔坐标到极坐标导致 NaN

javascript - 你能用 JavaScript 编写嵌套函数吗?