你最好的选择是找到一个接近你想要的缓动函数并调整持续时间。但是如果你真的想做一些自定义的事情,jQuery easing 插件可以让你使用以下函数指定时间:
jQuery.easing.newEasingMethodName (
x, // Ignored
current_time,
start_value,
end_value,
total_time
)
它在动画中的各个点被调用,并期望返回适合动画经过时间的位置。检查easeOutBounce
,您可以看到每个if
语句将进度标准化为总时间的百分比(t/=d
代码段),并应用 4 个论坛中的一个来导出当前值作为该百分比的函数。
问题是这些公式函数不是连续的——它们被单独“调整”以在时间线中那个精确的完成百分比点处拾取另一个离开的地方。例如,在下面的代码片段中,如果您选择“step”,您将看到动画从一个位置跳到另一个位置,没有中间动画。如果您只是从代码块中取出其中一条if
语句,就会发生这种情况easeOutBounce
——它会从一个步骤的完成跳到下一个步骤的开始,该步骤被调整为在时间线的后面部分开始,所以会导致你的动画到处乱跳。
您可以使用custom
下面的函数作为起点——它只是easeOutBounce
函数,经过重写以使其不那么晦涩难懂。
祝你好运。:)
var $div = $('#test');
var $easeMethodName = $('#method-name');
var $animationDuration = $('#animation-duration');
$('button').click(function() {
$div.toggleClass('expanded');
var width = $div.hasClass('expanded') ? 400 : 200;
var duration = parseInt($animationDuration.val(), 10);
$div.animate({
width: width
}, {
duration: duration,
easing: $easeMethodName.val()
});
});
var linear = function(ignore, t, start_value, end_value, d) {
var pct = t/d;
return pct * end_value;
};
$.easing.linear = linear;
var step = function(ignore, t, start_value, end_value, d) {
var pct = t/d * 100;
var step = Math.round(pct / 25);
return (step * .25) * end_value + start_value;
};
$.easing.step = step;
// This is the eastOutBounce function, rewritten to make it a little
// easier to read. Use it as a starting point for modification.
// t is the current time; d is the duration of the animation
var custom = function(ignore, t, start_value, end_value, d) {
var pct = t/d;
var step1 = 1/2.75; // ~36%
var step2 = 2/2.75; // ~73%
var step3 = 2.5/2.75; // ~90%
if (pct < step1) {
return end_value*(7.5625*pct*pct) + start_value;
} else if (pct < step2) {
return end_value*(7.5625*(pct-=(1.5/2.75))*pct + .75) + start_value;
} else if (pct < step3) {
return end_value*(7.5625*(pct-=(2.25/2.75))*pct + .9375) + start_value;
} else {
return end_value*(7.5625*(pct-=(2.625/2.75))*pct + .984375) + start_value;
}
};
$.easing.custom = custom;
#test {
width: 200px;
height: 20px;
border: 1px solid #900;
background: #ccc;
position: relative;
margin-top: 1em;
}
label, button {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script>
<label>Method name:
<select id="method-name">
<option value="linear">Linear</option><option value="step">Step</option><option value="custom">Custom</option><option value="easeInOutBounce">easeInOutBounce</option>
</select>
</label>
<label>Duration:
<input id="animation-duration" value="1000" />
</label>
<button>Animate</button>
<div id="test">
</div>