$(element).animate(
{
scale: 1,
centerX: -(this.chartObj.model.m_AreaBounds.Width /2),
centerY:-(this.chartObj.model.m_AreaBounds.Height /2)
},
{
duration: 2000,
step: function(now,fx) {
var scaleVal, x, y;
if (fx.prop == "scale") {
scaleVal = now;
x = 0;
y = 0;
} else if (fx.prop == "centerX") {
x = now;
y = 0;
scaleVal = 0;
}
else if (fx.prop == "centerY") {
x = 0;
y = now;
scaleVal = 0;
}
$(element).attr("transform", "translate("+x*(scaleVal-1)+","+(y*scaleVal-1)+")scale(" + now + ")");
}
}
);
在步骤函数中,prop值将逐步进行(即,首先scale
,然后是centerX
,然后是centerY
)。我想使用CSS转换属性设置所有这些值,即。我希望只需一步即可获得所有属性值。
答案 0 :(得分:5)
您可以使用fx
对象在逐步执行变量时将值存储到变量中,然后在最终的CSS声明中一次性使用它们。
您的问题是将所有其他变量设置为0,这可以通过实例化动画函数的外部来避免,然后只在每个条件语句中设置一个变量。这将允许他们在迭代之间保持其值。
以下是使用您的代码的示例(只需进行一些更改以更好地适应演示):
$(document).ready(function () {
var scaleVal, x, y;
scaleVal = x = y = 0;
$({scale: 0, centerX: 0, centerY: 0}).animate({
scale: 1,
centerX: 100,
centerY: 200
}, {
duration: 2000,
step: function (now, fx) {
if (fx.prop == "scale") {
scaleVal = now;
} else if (fx.prop == "centerX") {
x = now;
} else if (fx.prop == "centerY") {
y = now;
}
$('div').css("-webkit-transform", "translate(" + x * (scaleVal - 1) + "%," + (y * scaleVal - 1) + "%)scale(" + scaleVal + ")");
}
});
});
div {
width: 50px;
height: 50px;
background: #bbb;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
答案 1 :(得分:0)
只有在所有属性都有值时才应为元素设置动画。这将减少回流次数并创建更流畅的动画。
var animatedProperties = {scale: 0, x: 0, y: 0},
animatedPropertiesLength = 3,
updatedProperties = 0,
targetElement = $('#target');
$({
scale: 0,
x: 0,
y: 0
}).animate({
scale: 1,
x: 100,
y: 200
}, {
step: function (now, fx) {
animatedProperties[fx.prop] = now;
if (++updatedProperties == animatedPropertiesLength) {
updatedProperties = 0;
targetElement.css('-webkit-transform', 'translate(' + animatedProperties.x * (animatedProperties.scale - 1) + '%,' + (animatedProperties.y * animatedProperties.scale - 1) + '%)scale(' + animatedProperties.scale + ')');
}
}
});
#target {
width: 50px;
height: 50px;
background: #bbb;
-webkit-transform: scale(0);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="target"></div>