2014-02-24 25 views
-2

在我的代碼中,我使用了1000毫秒作爲動畫函數中的持續時間值。現在我想用隨機值代替這個值。我該怎麼做?將隨機值作爲JQuery的動畫函數中的持續時間

<html> 
<body> 
<script src="jquery-1.11.0.min.js"></script> 
<script> 
$(document).ready(function() { 
$('#btn').click(function() { 
$('#i1').animate({ 
'margin-left': '+=1155px' 
},1000); 
}); 
</script> 
<img src="images.jpg" height="100px" width="200px" id="i1"><br> 
<input type="button" value="start" id="btn"> 
</body> 
</html> 
+1

你嘗試的東西之間的隨機數?有什麼問題? –

+0

在問你之前看看Math.random() –

+0

Google。 – bjb568

回答

1

它應該很簡單,因爲我認爲。

使用

Math.floor((Math.random()*100)+1); 

其中* 100要生成的最大值。

<script src="jquery-1.11.0.min.js"></script> 
<script> 
jQuery(function($){ // Dom ready shorthand 
    $('#btn').click(function() { 
     $('#i1').animate({ 
     'margin-left': '+=1155px' 
     }, Math.floor((Math.random()*1000)+1)); 
    }); 
}); 
</script> 

如果您需要在多個地方重用你隨機你可以有一些有趣用自己的可重複使用的方法:

var MM = { // My Methods 
    rand : function(min,max) { // RANDOMIZER 
     return Math.floor(Math.random()*(max-min+1)+min); 
    }, // comma separate 
    something : function() { 
     // return your other method 
    } 
} 

,並使用像MM.rand(minValue , maxValue);

$('#i1').animate({marginLeft: '+=1155'}, MM.rand(200, 1000)); 
0

可以生成隨機數爲持續時間參數amimate() fu nction 那麼你的代碼變得

$(document).ready(function() { 
$('#btn').click(function() { 
$('#i1').animate({ 
'margin-left': '+=1155px' 
},Math.floor((Math.random()*2000)+1000)); 
}); 

這裏產生1000年和2000年

+0

以及已經回答了 –