2016-04-06 6 views
0

いくつかのボタンをアニメーション化しようとしています。アニメーションボタンは常に同じシーケンスではないランダムな文字列を生成する必要があります。 fiddle要素をランダムシーケンスでアニメーション化する

例:

text = 1423 

最初のアニメーションのボタンであるbtn1次いで後1秒btn4次いで、1秒後btn2次いで一秒btn3

ボタン後:

<div> 
    <button name="btn1" type="submit" id="btn1" value="1" style="" class="button"></button> 
    <button name="btn2" type="submit" id="btn2" value="2" style="" class="button"></button> 
    </div> 
    <div> 
    <button name="btn3" type="submit" id="btn3" value="3" style="" class="button"></button> 
    <button name="btn4" type="submit" id="btn4" value="4" style="" class="button"></button> 
</div> 

javascript:

var textArray = []; 
var text = ""; 
function makeid() 
{ 

    var possible = "1234"; 

    for(var i=0; i < 4; i++) 
     text += possible.charAt(Math.floor(Math.random() * possible.length)); 

    return text; 
} 
makeid(); 
textArray = text.split(""); 
console.log(textArray); 

function animate1() { 

$('#btn' + textArray[0]).animate({ backgroundColor: 'red' }, 500);  
} 
function animate2() { 

$('#btn' + textArray[1]).animate({ backgroundColor: 'red' }, 500); 
} 
function animate3() { 

    $('#btn' + textArray[2]).animate({ backgroundColor: 'red' }, 500);  
} 
function animate4() { 

$('#btn' + textArray[3]).animate({ backgroundColor: 'red' }, 500); 
} 

window.setTimeout(animate1, 1000); 
window.setTimeout(animate2, 2000); 
window.setTimeout(animate3, 3000); 
window.setTimeout(animate4, 4000); 

答えて

2

possible textのシャッフルに関する問題は、機能上同じ番号が繰り返される可能性があるためです。 2,2,2,1または4,4,4,4などとなります。

あなたの代わりにシャッフルのあなたの方法のこのシャッフル機能を使用することができます。

function shuffleWord(word) { 
    var shuffledWord = ''; 
    var charIndex = 0; 
    word = word.split(''); 
    while (word.length > 0) { 
     charIndex = word.length * Math.random() << 0; 
     shuffledWord += word[charIndex]; 
     word.splice(charIndex, 1); 
    } 
    return shuffledWord; 
} 

アップデートした後、あなたの例のJsFiddleを参照してください。

0

jQuery.Colorプラグインが使用されていない限り、あなたはすべてのアニメーション化されたプロパティは、以下に示すよう除き、単一の数値、 にアニメ化されなければならない

jQuery animate docs

backgroundColorをアニメーション化することはできません。数字以外のほとんどのプロパティは、 jQuery.Colorプラグインが使用されていない限り、基本的なjQuery機能(たとえば、幅、高さ、 または左にアニメーションを付けることはできますが、背景色にすることはできません)

ランダムオーダーの作成時に重複IDを許可します。また、コードを簡略化することができます。

var textArray = []; 

function makeid() { 
    var num; 
    var possible = "1234"; 

    while(textArray.length < 4) { 
     num = possible.charAt(Math.floor(Math.random() * possible.length)); 

     if (textArray.indexOf(num) === -1) { 
      textArray.push(num) 
     } 
    } 
} 

function animate(id, wait) { 
    setTimeout(function() { 
    $('#btn' + id).animate({ width: '200'}, 500); 
    }, wait); 
} 

makeid(); 
for (var i=0; i < textArray.length; i++) { 
    animate(textArray[i], i * 1000) 
} 

fiddle

関連する問題