jquery - 如何在这个 jQuery 代码段中添加自定义的缓动函数而不获取所有的 jQueryUI?
问题描述
linear
我看到有人使用一种算法来模拟仅使用参数的easeOutExpo 效果。下面这段代码的缺点是它需要计算:
step_value += (target_value - step_value)/25
. 在代码中看起来很奇怪。
在这种情况下,如何将缓动函数直接分配给 jQuery?在这种情况下是否可以只应用缓动函数而不在代码中引入 jQuery UI 或任何其他繁重的框架?
var step_value = 0;
var target_value = 90;
$({
someValue: 0
}).animate({
someValue: target_value
}, {
duration: 6800,
easing: 'linear',
step: function() {
step_value += (target_value - step_value)/25;
$('#text1').val(step_value);
},
complete: function(){
$('#text1').val(target_value).css('color', 'red');
}
});
/* This is my goal:
$({
someValue: 0
}).animate({
someValue: target_value
}, {
duration: 6800,
easing: 'easeOutExpo',
step: function() {
$('#text1').val(this.someValue);
},
complete: function(){
$('#text1').val(this.someValue).css('color', 'red');
}
});
*/
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="text1" />
解决方案
您可以从 jQueryUI 脚本(此处为 v1.12.1 )中复制您需要的部分。最后你得到这个:
(function() {
var baseEasings = {};
$.each(["Quad", "Cubic", "Quart", "Quint", "Expo"], function(i, name) {
baseEasings[name] = function(p) {
return Math.pow(p, i + 2);
};
});
$.extend(baseEasings, {
Sine: function(p) {
return 1 - Math.cos(p * Math.PI / 2);
},
Circ: function(p) {
return 1 - Math.sqrt(1 - p * p);
},
Elastic: function(p) {
return p === 0 || p === 1 ? p :
-Math.pow(2, 8 * (p - 1)) * Math.sin(((p - 1) * 80 - 7.5) * Math.PI / 15);
},
Back: function(p) {
return p * p * (3 * p - 2);
},
Bounce: function(p) {
var pow2,
bounce = 4;
while (p < ((pow2 = Math.pow(2, --bounce)) - 1) / 11) {}
return 1 / Math.pow(4, 3 - bounce) - 7.5625 * Math.pow((pow2 * 3 - 2) / 22 - p, 2);
}
});
$.each(baseEasings, function(name, easeIn) {
$.easing["easeIn" + name] = easeIn;
$.easing["easeOut" + name] = function(p) {
return 1 - easeIn(1 - p);
};
$.easing["easeInOut" + name] = function(p) {
return p < 0.5 ?
easeIn(p * 2) / 2 :
1 - easeIn(p * -2 + 2) / 2;
};
});
})();
var step_value = 0;
var target_value = 90;
$({
someValue: 0
}).animate({
someValue: target_value
}, {
duration: 6800,
easing: 'easeOutExpo',
step: function() {
$('#text1').val(this.someValue);
},
complete: function() {
$('#text1').val(this.someValue).css('color', 'red');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="text1" />
当然,你可以只选择你需要的缓动并且你可以缩小代码。
也在JSFiddle上。
推荐阅读
- javascript - 使用符号或数字重命名解构对象键
- testing - 如何通过TestCafe中的层次结构遍历嵌套的框架树?
- push-notification - Ionic 4、Firebase-x 和 FCM 带有操作按钮的推送通知
- kivy - .kv 文件中的 MDDataTable
- python - docker内部的Django服务器导致机器人测试出现空白屏幕?
- javascript - 如何让我的 Discord 机器人读取谁将用户从语音频道中移出?
- kubernetes - 在 Kubernetes YAML 中引用资源属性
- java - Hibernate 和 MYSQL:您的 SQL 语法有错误?
- graphql - 如何在空手道中将数据注入graphql文件
- c# - 列表到 DataGrid 的 WPF DataBinding - 不更新数据网格