使用 CSS 动画更改显示和不透明度 [英] Changing display and opacity with CSS animation

查看:23
本文介绍了使用 CSS 动画更改显示和不透明度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下按钮:

HTML:

<button id='foo' style='display: none; opacity: 0'>Foo</button>

CSS:

    #foo {
      transition: opacity .5s ease-in-out;
      -moz-transition: opacity .5s ease-in-out;
      -webkit-transition: opacity .5s ease-in-out;
    }

JS:

  $('#foo').css('display', '');
  $('#foo').css('opacity', '');

它在某种意义上起作用了,按钮确实出现了,但没有动画.所以我不确定这里有什么问题.有人知道吗?

It's working in a sense, the button does appear, but without the animation. So I am not sure what's the issue here. Does anyone have any idea ?

此外,我不希望建议提及可见性,因为这不是这里的重点.谢谢!

Also, I don't want suggestions mentioning visibility because that's not the point here. Thanks !

推荐答案

您应该将 display 属性的设置与动画中涉及的属性的设置分开.如果您在一轮中设置它们,动画将不会运行(问题在于 display: none).一种方法是执行 setTimeout.

You should separate setting the display property from setting the properties involved in the animation. If you set them in one round the animations won't run (the problem is with display: none). One way is to do a setTimeout.

另外,我的建议是永远不要更改 JS 的样式属性,始终操作类以更好地分离.像这样的事情会做:

Also, my suggestion is to never change style properties from JS, always manipulate classes for better separation. Something like this will do:

var $foo = $('#foo').addClass('display');
 
setTimeout(function () {
  $foo.addClass('show');
});
 

#foo {
  transition: opacity 1s ease-in-out;
  opacity: 0;
  display: none;
}

#foo.display {
  display: inline-block;
}

#foo.show {
  opacity: 1;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id='foo'>Foo</button>

这篇关于使用 CSS 动画更改显示和不透明度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆