在 javascript css 属性中使用变量

Using variables in javascript css property

本文关键字:变量 属性 javascript css      更新时间:2023-09-26

我对Javascript比较陌生,正在尝试制作一个简单的游戏,其中流星以随机的速度坠落。我的问题是,每次播放 for 循环时,流星div 都应该在它与顶部的距离上添加数学运算,但我不知道该怎么做。看看当前的代码,你会发现 #meteor 用"math"动画。此代码不起作用。关于如何使其工作的任何想法?

谢谢,感谢您的投入!

var math = Math.round(Math.random * 5)
        for(var i = 0; i <= height / 3; i++) {
            $('#meteor').animate({top: "+=math"}, 1)
        }

有几件事。每当用引号将JS中的任何内容括起来时,它都被视为字符串,因此即使您有变量math,因为它在引号中,因此被视为字符串'math'。另一件事是+=必须有一些东西才能工作,并且不能以你尝试的方式与jQuery一起使用。

要简化代码工作,请将其更改为以下内容:

var math = Math.round(Math.random * 5)
for(var i = 0; i <= height / 3; i++) {
    // Gives the 'top' value for meteor. parseInt removes the
    // 'px' that will show up on the end and return type int
    var meteorTop = parseInt($('#meteor').css('top')); 
    $('#meteor').animate({top: meteorTop + math}, 1);
}
也就是说,您的动画将

重叠,您将希望在动画之间等待,否则它们将相互触发,而不是按照您想要的方式工作。

唯一相关的,+=工作的情况是这样的:

var int = 0;
int += 2; // int = 2; this is the same as: int = int + 2;
int += 3; // int = 5; this is the same as: int = int + 3;
你应该将

相同的类型添加到自身,JS会为你做一些解释,但你应该始终使用相同类型的+=string += stringint += int.

尝试遵循一个

 for(var i = 0; i <= height / 3; i++) {
    var math = Math.round(Math.random * 5)
    $('#meteor').animate({top: "+="+math}, 1);
 }

如果您尝试在每次迭代时通过数学递增 top 的值,那么您需要类似以下内容:

  $('#meteor').animate({top: math * i}, 1)