MST

星途 面试题库

面试题:JavaScript 批量修改 DOM 样式与动画过渡的协同实现

假设页面中有一系列 DOM 元素,现在要批量修改它们的样式,并为样式变化添加流畅的动画过渡效果。要求使用 JavaScript 结合 CSS3 动画来实现,且要考虑不同浏览器的兼容性,同时处理动画完成后的回调逻辑。请给出完整的实现代码和详细的思路说明。
18.6万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试

思路说明

  1. 选择 DOM 元素:使用 querySelectorAll 方法选中需要修改样式的一系列 DOM 元素。
  2. 添加 CSS 类:通过 JavaScript 为这些元素添加一个新的 CSS 类,该类包含我们想要应用的样式变化以及动画过渡效果。
  3. 处理动画完成回调:为每个元素添加 animationend 事件监听器,当动画完成时执行回调函数。
  4. 兼容性处理:为了兼容不同浏览器,需要添加浏览器前缀。

实现代码

<!DOCTYPE html>
<html lang="en">

<head>
  <style>
    /* 定义初始样式 */
    .box {
      width: 100px;
      height: 100px;
      background-color: lightblue;
      margin: 10px;
      transition: none;
    }

    /* 定义动画过渡后的样式及动画效果 */
    .box.animate {
      width: 200px;
      height: 200px;
      background-color: lightgreen;
      /* 兼容不同浏览器的动画过渡 */
      -webkit-transition: width 0.5s ease, height 0.5s ease, background-color 0.5s ease;
      -moz-transition: width 0.5s ease, height 0.5s ease, background-color 0.5s ease;
      -ms-transition: width 0.5s ease, height 0.5s ease, background-color 0.5s ease;
      -o-transition: width 0.5s ease, height 0.5s ease, background-color 0.5s ease;
      transition: width 0.5s ease, height 0.5s ease, background-color 0.5s ease;
    }
  </style>
</head>

<body>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>

  <script>
    // 选择所有需要修改样式的 DOM 元素
    const boxes = document.querySelectorAll('.box');

    // 为每个元素添加动画完成的回调
    boxes.forEach((box) => {
      box.addEventListener('animationend', function () {
        console.log('动画完成');
        // 这里可以添加更多动画完成后的逻辑,比如移除类
        // this.classList.remove('animate');
      });
      box.addEventListener('webkitAnimationEnd', function () {
        console.log('动画完成(webkit 内核浏览器)');
        // 这里可以添加更多动画完成后的逻辑,比如移除类
        // this.classList.remove('animate');
      });
      box.addEventListener('mozAnimationEnd', function () {
        console.log('动画完成(Firefox 浏览器)');
        // 这里可以添加更多动画完成后的逻辑,比如移除类
        // this.classList.remove('animate');
      });
      box.addEventListener('MSAnimationEnd', function () {
        console.log('动画完成(IE 浏览器)');
        // 这里可以添加更多动画完成后的逻辑,比如移除类
        // this.classList.remove('animate');
      });
      box.addEventListener('oAnimationEnd', function () {
        console.log('动画完成(Opera 浏览器)');
        // 这里可以添加更多动画完成后的逻辑,比如移除类
        // this.classList.remove('animate');
      });
    });

    // 为所有元素添加动画类,触发样式变化和动画
    boxes.forEach((box) => {
      box.classList.add('animate');
    });
  </script>

</body>

</html>

以上代码通过选择页面中的 .box 元素,为它们添加 animate 类来触发样式变化和动画过渡,同时添加了不同浏览器的动画完成事件监听器以处理回调逻辑。