jQuery CSS 淡入淡出 onclick

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30696642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:43:19  来源:igfitidea点击:

CSS fadein fadeout onclick

jqueryhtmlcss

提问by ServerSideSkittles

I am trying to use CSS animations on a div which is shown/hidden using toggle().

我正在尝试在使用 .css 显示/隐藏的 div 上使用 CSS 动画toggle()

I have added ease-in-outon my animation but it only fades in and will not fade out.

我已经添加ease-in-out了我的动画,但它只会淡入而不会淡出。

Here is my css:

这是我的CSS:

#form {
display: none;
animation: formFade 2s ease-in-out;
-moz-animation: formFade 2s ease-in-out; /* Firefox */
-webkit-animation: formFade 2s ease-in-out; /* Safari and Chrome */
-o-animation: formFade 2s ease-in-out; /* Opera */
}

@keyframes formFade {
from {
    opacity:0;
}
to {
    opacity:1;
}
}
@-moz-keyframes formFade { /* Firefox */
from {
    opacity:0;
}
to {
    opacity:1;
}
}
@-webkit-keyframes formFade { /* Safari and Chrome */
from {
    opacity:0;
}
to {
    opacity:1;
}
}
@-o-keyframes formFade { /* Opera */
from {
    opacity:0;
}
to {
    opacity: 1;
}
}

Here is the html/js:

这是 html/js:

<form id="form" >
TEST
</form>

<script>
            $('#formButton').on('click', function() {
            $("#form").toggle();

            });
        </script>  

It fades in onclickbut doesn't fade out. Any ideas why?

它淡入onclick但不淡出。任何想法为什么?

回答by AlliterativeAlice

Using .toggle()to hide an element just sets it to display: nonewithout affecting the opacity. Try this:

使用.toggle()隐藏的元素只是把它设置为display: none不影响透明度。尝试这个:

$('#formButton').on('click', function() {
    if ($('#form').css('opacity') == 0) $('#form').css('opacity', 1);
    else $('#form').css('opacity', 0);
});
#form {
    opacity: 0;
    -webkit-transition: all 2s ease-in-out;
    -moz-transition: all 2s ease-in-out;
    -ms-transition: all 2s ease-in-out;
    -o-transition: all 2s ease-in-out;
    transition: all 2s ease-in-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="form">Test</div>

<a href="#" id="formButton">Click</a>