如果我有这个:
.circle {
height: 20px;
width: 20px;
border-radius: 10px;
}
我可以动画缩放它的大小如下:
$('.circle').animate({
'height' : 40px,
'width' : 40px,
'border-radius': 20px
});
但是,最好的方法是将它缩减回原来的css(使用动画,所以只是剥离内联的html风格不会起作用)?
我可以想到两种方式:
如果有多个字段,第二种方法的缺点是需要很多变量和代码行。
我不是jQuery的专家,我认为必须有一种我更容易丢失的方式。
答案 0 :(得分:6)
我建议您使用CSS在jQuery中设置表示层和toggleClass,以通过切换类来添加和删除CSS属性。
在这种情况下,使用jQuery toggleClass()
而不是addClass()
和removeClass()
可以避免使用if else语句来检查类.animated
是否已经存在.circle
} class。
JS / jQuery
$('.circle').click(function(){
$(this).toggleClass('animated');
});
<强> CSS 强>
.circle {
height: 200px;
width: 200px;
border-radius: 100px;
transition: all .5s ease;
background-color:red;
}
.circle.animated {
height: 400px;
width: 400px;
border-radius: 200px;
background-color:blue;
transition: all .5s ease;
}
我编辑了圆的尺寸,使其更加明显,也改变了背景颜色。如果单击它,您将看到CSS应用的过渡。 通过这种方式,您可以保持代码清洁,并且通过编辑每个类的CSS属性来更容易编辑。
DEMO http://jsfiddle.net/eNUpJ/12/
良好的经验法则:
HTML
用于演示的 CSS
JS(或jQuery作为JS框架)用于行为
答案 1 :(得分:3)
之后直接进行过渡。
$('.circle').animate({
'height' : 40px,
'width' : 40px,
'border-radius': 20px
},'fast', function(event) {
$('.circle').animate({
'height' : 20px,
'width' : 20px,
'border-radius': 10px
}'slow');
答案 2 :(得分:0)
尝试
$(function () {
$(".circle").animate({
"height": "40px",
"width": "40px",
"border-radius": "20px"
}, {
duration: 2500,
done: function (promise) {
var back = {};
$.each(promise.props, function (key, value) {
back[key] = String(Number(value.replace("px", "") / 2) + "px");
});
return $(this).animate(back, promise.duration);
}
});
});
jsfiddle http://jsfiddle.net/guest271314/5vY2s/
请参阅 http://api.jquery.com/animate/#animate-properties-options