【问题标题】:Animation in javascript with DOM insted of Jquery使用 DOM 而不是 Jquery 的 javascript 动画
【发布时间】:2021-12-14 22:09:39
【问题描述】:

是否可以使用 DOM 而不是 Jquery 重新创建此动画?如果有怎么办?

$('.bubbles-animation')
  .animate({
    'bottom': '100%',
    'opacity' : '-=0.7'
   }, 2000, function(){
     $(this).remove()
   }
);

【问题讨论】:

    标签: javascript jquery animation dom


    【解决方案1】:

    jQuery 只是底层的 js 和 css。在 vanilla js 中重新创建任何 jquery 操作是绝对可能的。如果您想创建 jquery 操作的 1:1 副本,您可以检查源代码以了解 jquery 是如何完成任务的。但是,如果您只需要使用 vanilla js 创建动画然后删除元素,这里有一个演示如何完成。

    我的整个代码 sn-p 被包装在一个异步匿名函数中,该函数将立即被调用。这可以防止在我的代码范围内发生命名冲突,还允许我访问 await 关键字。

    首先我创建了两个辅助函数。 $ 会成功,这样我就可以以类似于 jquery 的方式从 DOM 中获取元素。 wait 辅助函数返回一个在超时后解析的承诺。

    我会等待 1000 毫秒或 1 秒,然后再根据个人喜好更改不透明度以更改动画的时间。

    更改不透明度后,我再等待 2 秒,这也是过渡显示所需的时间,然后删除元素。

    请记住,这只会针对具有bubbles-animation 类的第一个元素,我还想补充一点,我个人更喜欢在高度上更改过渡而不是不透明度,因为它可以更平滑地折叠其他元素我个人认为。

    css 很容易解释,但如果您有任何问题,我建议您查看this demo

    (async () => {
      const $ = str => document.querySelector(str);
      const wait = t => new Promise(r => setTimeout(r, t));
      
      await wait(1000);
      $(".bubbles-animation").style.opacity = "0.3";
      await wait(2000);
      $(".bubbles-animation").remove();
    })();
    .bubbles-animation {
      transition: opacity 2s;
    }
    <div class="bubbles-animation">Vanish!</div>
    <div>Stay!</div>

    【讨论】:

      【解决方案2】:

      是的,您可以依靠 CSS 过渡来实现它。但是,这取决于您要达到的目标。没有足够的信息在反射中走得更远。

      https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transitions/Using_CSS_transitions

      document.getElementById('css-js')
        .addEventListener('click',
          () => document.querySelector('.bubbles').classList.add('animation'))
      
      document.getElementById('reset')
        .addEventListener('click',
          () => document.querySelector('.bubbles').classList.remove('animation'))
      #settings {
        position: fixed;
        top: 0px;
      }
      
      .bubbles {
        position: absolute;
        height: 100%;
        top: 0px;
        width: 100%;
      
        background-color: green;
      
        transition-property: transform, opacity;
        transition-duration: 2s, 1.5s;
      }
      
      .animation {
        opacity: 0;
        transform: translateY(-100%);
      }
      <div class=bubbles></div>
      
      <div id=settings>
        <button id=css-js>CSS &amp; Native JS</button>
        <button id=reset>Reset</button>
      </div>

      【讨论】:

        猜你喜欢
        • 2011-07-21
        • 2012-11-07
        • 2019-01-26
        • 2016-10-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多