簡體   English   中英

在javascript CSS屬性中使用變量

[英]Using variables in javascript css property

我對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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM