如何在此jQuery代码段中添加自定义缓动函数而又不获取所有jQueryUI?

问题描述 投票:0回答:1

[我看到有人使用一种算法来仅通过linear参数来模拟easyOutExpo效果。以下这段代码的缺点是需要进行计算: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" />
jquery easing jquery-easing easing-functions
1个回答
0
投票

您可以从jQueryUI脚本(v1.12.1 here)复制所需的部分。最后,您得到以下信息:

(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上。

© www.soinside.com 2019 - 2024. All rights reserved.