2012-12-25 99 views
4

我想我忽略了一些東西。這是一個非常簡單的旋轉瓶遊戲。第二次點擊時旋轉DIV緩慢旋轉

的Javascript/jQuery的

$('.bottle').on('click', function(e) { 
    this.removeAttribute('style'); 
    var deg = 3000 + Math.round(Math.random() * 500); 
    var css = '-webkit-transform: rotate(' + deg + 'deg);'; 

    this.setAttribute(
     'style', css 
    ); 
}); 

CSS:

.bottle { 
    width: 200px; 
    height: 200px; 
    background-image: url(img/bottle.png); 
    -webkit-transition: -webkit-transform 6s ease-out; 
} 

HTML:

<div class="bottle"></div> 

這工作完全在瓶子上的第一次點擊。但從第二次點擊開始,旋轉非常慢?

回答

7

試試這個:http://jsfiddle.net/sMcAN/

var i = 1; 
$('.bottle').on('click', function(e) { 
this.removeAttribute('style'); 
var deg = 3000 + Math.round(Math.random() * 500); 
deg = ((-1)^i) * deg; 

var css = '-webkit-transform: rotate(' + deg + 'deg);'; 
this.setAttribute('style', css); 
i++; 
});​ 

另一個更新:http://jsfiddle.net/sMcAN/2/

+0

+1的工作演示。 @MartinLyder:我會關注任何解決方案的事情是繼續增加/減少度數,事後我會認爲你達到了內存不足的例外。我不知道如果最大度數是一個最大的整數/長或小數等... – Nope

+0

哦,我發現一個錯誤,「deg」在每次嘗試後都在上升。因此,演示中的徽標速度正在增加每次點擊後... –

+0

@MartinLyder:查看更新後的[小提琴](http://jsfiddle.net/sMcAN/2/),每次點擊旋轉方向改變... – Anujith

0
math.round(math.random() * 1000); 

試一下

3

這是因爲,第一,您是從0比3000要值但隨後,該值總是在3000 - 這樣的差異不夠大,它仍然需要你定義的6秒鐘。

一個解決方案是確保您抵消價值並使其每次有數千次不同。

var i = 0, offset = [2000, 4000, 6000, 3000, 5000, 1000]; 

$('.bottle').on('click', function(e) { 
    this.removeAttribute('style'); 

    var deg = offset[i] + Math.round(Math.random() * 500); 
    i++; 
    if (i > 5) { 
    i = 0; 
    } 

    var css = '-webkit-transform: rotate(' + deg + 'deg);'; 

    this.setAttribute(
    'style', css 
); 
});​ 
+0

+1解釋爲什麼旋轉的行爲方式是這樣。我認爲OP期望這個度數是累積的,而不是。爲了繼續旋轉瓶子,如果第一次旋轉之後的最終度數可以設置爲div的新的0度位置並且因此具有相同度數設置的新旋轉將保持工作並向前旋轉,那麼將會是甜蜜的。 – Nope

+0

是弗朗索瓦瓦爾的好點。這將是一個偉大的功能:)並感謝Dakdad這是一個很好的方式,使瓶子更隨機像... –

+0

我想我會最終制定一個解決方案,用戶將有可能通過滑塊設置偏移量(速度,力量或類似的東西) –