指定した範囲内の数値をsetTimeoutを使って往復させてみます。
サンプルコード
HTML
1 | < div id = "sample" ></ div > |
CSS
1 2 3 4 5 6 7 8 | #sample { position : absolute ; top : 100px ; left : 100px ; width : 200px ; height : 200px ; background : #999 ; } |
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | var target = document.getElementById( 'sample' ); // 対象の要素 var max = 200; // 最大値 var min = 0; // 最小値 var count = 100; // カウンター var direction = 'right' ; // 進行方向 var time = 30; // アニメーションの速さ function animation() { // 進行方向が右で、カウンターが最大値を超えている場合 if (direction == 'right' && count > max) { direction = 'left' ; // 進行方向の変更 // 進行方向が左で、カウンターが最小値より小さい場合 } else if (direction == 'left' && count < min) { direction = 'right' ; // 進行方向の変更 } // 進行方向が右のとき if (direction == 'right' ) { count++; // カウンターに1プラスする // 進行方向が左のとき } else if (direction == 'left' ) { count--; // カウンターに1マイナスする } target.style.left = count + 'px' ; // 対象要素のポジション変更 setTimeout(animation, time); // animationの再実行 } animation(); |
指定した範囲内の数値を往復するデモページ
進行方向に応じてcountの数値を変更して、対象のポジションを変更してアニメーションにしています。
進行方向が右の場合は最大値を超えたら、左の場合は最小値より小さい場合に進行方向を変更してループになるようにしています。
コメントが承認されるまで時間がかかります。