二つの要素(aとb)にアニメーションをつけてランダムに動かしたいです。 同じコードを二つ書いてもどちらか一つにしかアニメーションが適応されません。
html
1<div class='a'></div> 2<div class='b'></div>
css
1div.a { 2width: 50px; 3height:50px; 4 background-color:red; 5position:fixed; 6 7} 8div.b { 9width: 50px; 10height:50px; 11 background-color:black; 12position:fixed; 13 14}
Javascript
1$(document).ready(function(){ 2 animateDiv(); 3 4}); 5 6function makeNewPosition(){ 7 8 // Get viewport dimensions (remove the dimension of the div) 9 var h = $(window).height() - 50; 10 var w = $(window).width() - 50; 11 12 var nh = Math.floor(Math.random() * h); 13 var nw = Math.floor(Math.random() * w); 14 15 return [nh,nw]; 16 17} 18 19function animateDiv(){ 20 var newq = makeNewPosition(); 21 var oldq = $('.a').offset(); 22 var speed = calcSpeed([oldq.top, oldq.left], newq); 23 24 $('.a').animate({ top: newq[0], left: newq[1] }, speed, function(){ 25 animateDiv(); 26 }); 27 28}; 29 30function calcSpeed(prev, next) { 31 32 var x = Math.abs(prev[1] - next[1]); 33 var y = Math.abs(prev[0] - next[0]); 34 35 var greatest = x > y ? x : y; 36 37 var speedModifier = 0.1; 38 39 var speed = Math.ceil(greatest/speedModifier); 40 41 return speed; 42 43} 44$(document).ready(function(){ 45 animateDiv(); 46 47}); 48 49function makeNewPosition(){ 50 51 // Get viewport dimensions (remove the dimension of the div) 52 var h = $(window).height() - 40; 53 var w = $(window).width() - 40; 54 55 var nh = Math.floor(Math.random() * h); 56 var nw = Math.floor(Math.random() * w); 57 58 return [nh,nw]; 59 60} 61 62function animateDiv(){ 63 var newq = makeNewPosition(); 64 var oldq = $('.b').offset(); 65 var speed = calcSpeed([oldq.top, oldq.left], newq); 66 67 $('.b').animate({ top: newq[0], left: newq[1] }, speed, function(){ 68 animateDiv(); 69 }); 70 71}; 72 73function calcSpeed(prev, next) { 74 75 var x = Math.abs(prev[2] - next[2]); 76 var y = Math.abs(prev[0] - next[0]); 77 78 var greatest = x > y ? x : y; 79 80 var speedModifier = 0.1; 81 82 var speed = Math.ceil(greatest/speedModifier); 83 84 return speed; 85 86}
回答1件
あなたの回答
tips
プレビュー