可以使jQuery的.animate()方法影响变量,而不是CSS属性吗? [英] Can jQuery's .animate() method be made to affect variables, rather than CSS properties?

查看:110
本文介绍了可以使jQuery的.animate()方法影响变量,而不是CSS属性吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始编写一些JS代码,使变量值随着时间的推移而增加,达到目标值,并采用某种形式的缓入。

I started writing some JS code to cause a variables value to increase over time, up to a target value, with some form of 'ease-in'.

我意识到jquery已经在它的.animate()方法中做到了这一点。当然,该方法用于操作CSS属性,而不是一般变量。

I realised that jquery already does this in it's .animate() method. Of course, the method is for manipulating CSS properties, not general variables.

我的问题是,是否可以做任何事情来破解它,以便该方法影响一个变量,而不是CSS属性?

My question is, is there anything that can be done to hack it so that the method affects a variable, rather than a CSS property?

推荐答案

是的,你可以为变量设置动画。 在这里演示

Yes, you can animate variables. Demo here

$({ n: 0 }).animate({ n: 10}, {
    duration: 1000,
    step: function(now, fx) {
        $("div").append(now + "<br />");
    }
});

在这个例子中,我将 n 的动画从0增加到10第二。在动画期间调用步骤函数,从那里您可以在中检索当前值

In this example, I am animating n from 0 to 10 in 1 second. The step function is called during animation and from there you can retrieve the current value in now.

就我个人而言,我使用这种方法以非线性方式同时为几个css属性设置动画。

Personally, I used this technique to animate several css properties simultaneously in a non linear fashion.

Animate通过修改值来运行JS对象中声明的属性。虽然 animate 旨在更改CSS标量值,但它也可以安全地用于任何通用属性,只要是一个标量的。
实际上,您可以将CSS视为一组JS对象,其中属性例如是 top 保证金等。

Animate runs by modifying the value of properties declared in JS objects. Although animate is designed to change CSS scalar values, it can also safely be used for any generic property, as long value is a scalar one.
In fact, you can think of CSS as a set of JS objects, where properties are for example, top, margin etc.

请注意,以下脚本也是如此。他们将CSS 从0更改为10

Note that the following scripts do the same. They change CSS left from 0 to 10

$("#test").css('left', 0).animate({ left: 10 }, 1000);

$({ left: 0 }).animate({ left: 10 }, {duration: 1000, step: function(now, fx) {
  $("#test").css('left', now);
}});

或者,不使用 now 参数

var obj = { left: 0 };
$(obj).animate({ left: 10 }, {duration: 1000, step: function() {
      $("#test").css('left', obj.left);
}});

要查看它们的实际效果点击这里

To see them in action click here

这篇关于可以使jQuery的.animate()方法影响变量,而不是CSS属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆