我对 Javascript 比较陌生,正在尝试制作一个简单的游戏,其中 meteor 以随机速率掉落。我的问题是,每次播放 for 循环时, meteor 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 += string
或 int += int
。
关于javascript - 在 javascript css 属性中使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29270059/