隐藏侧边栏动画后如何执行代码?

时间:2018-09-20 20:10:01

标签: html css angular typescript bootstrap-4

让我们假设我具有如下所示的功能。与上面this.sidebarVisible = false;中所示代码关联的所有动画都将完成后,我想执行sidebarClode()。有什么想法我该怎么做?

ts:

  sidebarOpen() {
    const toggleButton = this.toggleButton;
    const html = document.getElementsByTagName('html')[0];

    setTimeout(function () {
      toggleButton.classList.add('toggled');
    }, 500);
    html.classList.add('nav-open');

    this.sidebarVisible = true;

  };

  sidebarClose() {
    const html = document.getElementsByTagName('html')[0];
    this.toggleButton.classList.remove('toggled');
    html.classList.remove('nav-open');

    this.sidebarVisible = false; // I want to execute this line of code after all the animations associated with the code shown above in sidebarClode() will be done. I mean three lines of code above this comment.
  };

  sidebarToggle() {

    if (this.sidebarVisible === false) {
      this.sidebarOpen();
    } else {
      this.sidebarClose();
    }
  };

html:

  <button style="right: 1vw;" class="navbar-toggler navbar-burger" type="button" data-toggle="collapse" data-target="#navbarToggler"
          aria-controls="navbarTogglerDemo02" aria-expanded="false" aria-label="Toggle navigation"
          (click)="sidebarToggle()" (transitionend)="this.printText()" >

1 个答案:

答案 0 :(得分:0)

使用CSS来进行动画处理,就像您似乎在做的那样,我不确定您是否可以准确地使用它,因为CSS显然没有动画完整的回调方法。

您可以使用setTimeout估算它,但这并不精确。您也可以使用轮询。例如,假设您知道动画完成后元素的不透明度将为0,则可以使用setInterval这样:

const interval = setInterval(() => {
  const el = document.getElementById('myElement')
  if (window.getComputedStyle(el).getPropertyValue("opacity") === 0) {
    clearInterval(interval)
    // execute your animate complete code here
  }
}, 100)

动画结束后,此间隔将立即停止触发。

但是,如果您愿意使用确实具有动画完整回调功能的jQuery。动画完成后将执行该功能。

文档在这里:http://api.jquery.com/animate/

以下是jQuery代码的示例:

$( "#clickme" ).click(function() {
  $( "#book" ).animate({
    opacity: 0.25,
    left: "+=50",
    height: "toggle"
  }, 5000, function() {
    console.log('Animation complete.')
  });
});