一个函数JQuery的速度不同

Different speeds for one function JQuery

本文关键字:速度 JQuery 函数 一个      更新时间:2023-09-26

我写了一个函数来为对象设置动画,但后来我决定添加一些其他对象,这些对象应该使用相同的参数但不同的速度设置动画。我不想复制粘贴编写的函数,但不知道如何以不同的速度调用它。你能帮我这么做吗?

var moveObjects = function() {
    setInterval(function() {
        $("#object1").animate({
            left: -110 + "%"
        }, 15000, "linear", function() {
            $(this).addClass('flip');
        });
        $("#object1").animate({
            left: 110 + "%"
        }, 15000, "linear", function() {
            $(this).removeClass('flip');
        });
    }, 1000);
};
$(document).ready(function() {
    moveObjects();
});

将硬编码值替换为函数的参数:

var moveObjects = function(animSpeed, delay) {
    setInterval(function() {
        $("#object1").animate({
            left: -110 + "%"
        }, animSpeed, "linear", function() {
            $(this).addClass('flip');
        });
        $("#object1").animate({
            left: 110 + "%"
        }, animSpeed, "linear", function() {
            $(this).removeClass('flip');
        });
    }, delay);
};
$(document).ready(function() {
    moveObjects(15000, 1000);
});

尝试以下操作:

var moveObjects = function(intervalTime) {
    setInterval(function() {
        $("#object1").animate({
            left: -110 + "%"
        }, 15000, "linear", function() {
            $(this).addClass('flip');
        });
        $("#object1").animate({
            left: 110 + "%"
        }, 15000, "linear", function() {
            $(this).removeClass('flip');
        });
    }, intervalTime);
};
$(document).ready(function() {
    moveObjects(); //<--Place the speed here that you want for each.
});