【问题标题】:CSS animation with jQuery on enter and leave进入和离开时使用 jQuery 的 CSS 动画
【发布时间】:2016-06-22 16:59:34
【问题描述】:

我有一个 jQuery,它在鼠标进入时添加动画类,并在鼠标离开元素时添加另一个类,基本上我想要进出动画。我正在实现淡入淡出动画,但是当我用鼠标离开时,元素消失而没有动画。所以只有展示是动画的,而不是离开的。

jQuery:

$('.menu > ul > li').on({
            mouseenter: function () {
                if (getWindowWidth() >= responsiveBreakpoint) {
                    $(this).children('ul').removeClass('fadeOutUp').addClass('fadeInDown');
                }
            },
            mouseleave: function () {
                if (getWindowWidth() >= responsiveBreakpoint) {
                    $(this).children('ul').removeClass('fadeInDown').addClass('fadeOutUp');
                }
            }
        });

CSS

@keyframes fadeInDown {
  from {
    display: none;
    opacity: 0;
    transform: translate3d(0, -20px, 0);
  }

  to {
    display: block;
    opacity: 1;
    transform: none;
  }
}

.fadeInDown {
  animation: .2s ease;
  animation-name: fadeInDown;
}

@keyframes fadeOutUp {
  from {
    display: block;
    opacity: 1;
    transform: none;
  }

  to {
    display: none;
    opacity: 0;
    transform: translate3d(0, -20px, 0);
  }
}

.fadeOutUp {
  animation: .2s ease;
  animation-name: fadeOutUp;
}

我试图制作动画的元素的样式如下:

> ul {
        display: none;
        position: absolute;
        z-index: 99;
        left: 0;
        width: 100%;
        background: $hover-and-dropdown-bg;
}

【问题讨论】:

  • display 无法设置动画。或显示,或隐藏。不是中级。使用各种不透明度或类似的东西来实现相同的效果。但是,我认为您不需要 javascript 代码,您可以实现相同的纯 CSS(:hover 伪类),因为您的动画发生在儿童中。
  • 我设法在鼠标输入时动画显示看看我的代码如何,我只需要另一种方式,鼠标离开
  • 。您正在为 opacity 制作动画,但不是 display,因为按照规范和逻辑,动画 display 是不可能的
  • 你是对的,我没有为显示设置动画,因为它不可能,但你可以手动将显示块置于悬停状态,然后使用动画为其他属性设置动画。我在我的代码中确实做到了,如果它在输入时起作用,应该有一个离开的技巧
  • 我更喜欢纯css动画,但是不能像你用js的方案那样写延迟。问题仍然是display 动画,正如我告诉你的那样,这是不可能动画的。所以不用担心,使用自己的解决方案,以后可以测试纯css动画

标签: javascript jquery html css animation


【解决方案1】:

好的,所以我设法做到了,我欺骗了 css 让动画具有显示属性。

jquery

$('.menu > ul > li').on({
            mouseenter: function () {
                if (getWindowWidth() >= responsiveBreakpoint) {
                    $(this).children('ul').css('display', 'block').removeClass('fadeOutUp').addClass('fadeInDown');
                }
            },
            mouseleave: function () {
                if (getWindowWidth() >= responsiveBreakpoint) {
                    $(this).children('ul').removeClass('fadeInDown').addClass('fadeOutUp').delay(200).queue(function (next) {
                        $(this).css('display', 'none');
                        next();
                    });
                }
            }
        });

【讨论】:

    猜你喜欢
    • 2013-06-14
    • 1970-01-01
    • 1970-01-01
    • 2015-06-09
    • 1970-01-01
    • 2015-09-02
    • 1970-01-01
    • 1970-01-01
    • 2019-02-10
    相关资源
    最近更新 更多