2014-03-19 52 views
0

我試圖生成一個隨機數來追加到我的背景圖像網址作爲緩存驅動程序。問題是,當我將隨機數存儲在LESS變量中時,它每次都會計算javascript表達式。如何在LESS中一次生成一個隨機數並使用多次

@randomNum: `Math.ceil(Math.random() * 100000)`; 
div#div1{ 
    background: url("/assets/img/core/ui/[email protected]{randomnum}"); 
} 
div#div2{ 
    background: url("/assets/img/core/ui/[email protected]{randomnum}"); 
} 

兩個div都會向圖像發出請求,它們會有不同的隨機數。 這應該是預期的行爲?如果是這樣,有沒有人知道一種方式來存儲它,而不是每次評估它,所以我有一個相同的隨機數字符串追加到幾個調用相同的背景圖像?謝謝!

回答

0

你可以用變量聲明爲一個mixin,它會只進行一次評估,例如:

.constRandom() { 
    @randomNum: `Math.ceil(Math.random() * 100000)`; 
} .constRandom(); 

div#div1{ 
    background: url("/assets/img/core/ui/[email protected]{randomNum}"); 
} 
div#div2{ 
    background: url("/assets/img/core/ui/[email protected]{randomNum}"); 
}