Javascript toggle animation of height in Angular

白昼怎懂夜的黑 提交于 2019-12-12 04:05:49

问题


I have the following animation defined in my Angular app for toggling the hight/opacity of an element.

It works as expected, however I'm now using it to toggle a 'main menu' and the 'sub-menus' within.

When the main menu is opened it increases from 0 to X height, then if I open a sub menu the main menu remains at X height, whereas I'd like it to expand to the height of the main menu + height of the newly opened sub-menu.

app.animation('.slide_toggle', ['$animateCss',
  function ($animateCss) {
    return {
      addClass: function (element, className, done) {
        if (className == 'ng-hide') {
          var animator = $animateCss(element, {
            to: { height: '0px', opacity: 0 }
          });
          if (animator) {
            return animator.start().done(function () {
              element[0].style.height = '';
              done();
            });
          }
        }
        done();
      },
      removeClass: function (element, className, done) {
        if (className == 'ng-hide') {
          var height = element[0].offsetHeight;
          var animator = $animateCss(element, {
            from: { height: '0px', opacity: 0 },
            to: { height: height + 'px', opacity: 1 }
          });
          if (animator) {
            return animator.start().done(done);
          }
        }
        done();
      }
    };
  }
]);

I'm open to using a different animation method to the one above as long as the animation opens and closes smoothly.


回答1:


There were problems with all the 'Angular only' slide toggle methods I could find (mainly due to child element heights not being dealt with properly). In the end I included jQuery in the project and used the comprehensive slideUp and slideDown functionality from there like so:

myApp.animation('.slide', function () {
   return {
      beforeAddClass: function (element, className, done) {
         if (className === 'ng-hide') {
            element.slideUp({ duration: 350 }, done);
         }
      },
      removeClass: function (element, className, done) {
         if (className === 'ng-hide') {
            element.hide().slideDown({ duration: 350 }, done);
         }
      }
   }
});


来源:https://stackoverflow.com/questions/35135834/javascript-toggle-animation-of-height-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!