jQuery 使用动画切换类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18133440/
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
Toggle class with animation
提问by Code
I want to have something like this :
我想要这样的东西:
$('#fo').toggleClass('tra', 'slow');
I know that i can achieve this with jQuery UI but i'm looking for a faster and smaller solution because i don't wanna integrate in my site another 20-90 kb
我知道我可以使用 jQuery UI 实现这一点,但我正在寻找一个更快、更小的解决方案,因为我不想在我的网站中再集成 20-90 kb
回答by Hamza Kubba
Use .animate()
instead. You'll need to animate the individual styles that you want changed. E.g. .animate( { height: "500px", width: "200px" }, 2000 )
to change the height and width to those values over 2 seconds. jQuery UI lets you derive animations from class changes, pure jQuery doesn't.
使用.animate()
来代替。您需要为要更改的各个样式设置动画。例如.animate( { height: "500px", width: "200px" }, 2000 )
,在 2 秒内将高度和宽度更改为这些值。jQuery UI 允许您从类更改中派生动画,而纯 jQuery 则不能。
回答by Babatunde
Without JQuery UI, you'll probably have to CSS3 transitions/animations that trigger at the right time (see http://www.netmagazine.com/tutorials/getting-animations-trigger-right-time) or just .animate
with JQuery.
如果没有 JQuery UI,您可能必须使用在正确时间触发的 CSS3 转换/动画(请参阅http://www.netmagazine.com/tutorials/getting-animations-trigger-right-time)或仅.animate
使用 JQuery。
回答by kalley
You can do something like this(but it's not the cleanest):
你可以做一些这样的(但它不是最干净的):
function animateClass(el, klass) {
var endCSS = el.toggleClass(klass).css();
var startCSS = el.toggleClass(klass).css();
for ( var p in endCSS ) {
if ( startCSS[p] === endCSS[p] ) {
delete endCSS[p];
}
}
el.animate(endCSS, 'slow', function() {
el.toggleClass(klass).removeAttr('style');
});
};
It also assumes that you aren't going to add any other inline styles. Though I guess you could replace the animate callback with something like this:
它还假定您不打算添加任何其他内联样式。虽然我猜你可以用这样的东西替换动画回调:
for ( var p in endCSS ) {
endCSS[p] = '';
}
el.toggleClass(klass).css(endCSS);
It also uses a plugin that extends the use of $.fn.css
to return all CSS from How can I get list of all element css attributes with jQuery?
它还使用了一个插件,该插件扩展了$.fn.css
从如何使用 jQuery 获取所有元素 css 属性列表?
Short Answer
简答
CSS transitions.
CSS 过渡。
回答by Hemanth
Specify the animation name as a third parameter.
将动画名称指定为第三个参数。
$('#fo').toggleClass('big-blue', 'slow', "easeOutSine");