2016-10-02 11 views
0

キーダウンイベントリスナーでページを移動するdivがあります。私は一定の数のkeydowns(step * clicks> screen sizeで計算された)またはアニメーションdivが画面の最後に到達した後に停止する方法を見つけることを試みています。画面サイズ。ページ上の特定の位置でアニメーションを停止する[jQuery]

現在、アニメーションはkeydownで起動し、divは表示外にスクロールします。

この例は、このページの2番目のデモです。 ブロックが見えなくなるまで左または右をクリックできます。それをどうやってコンテナにするのですか?ここ

は私jsfiddleです:https://jsfiddle.net/vidro3/1a8tnuer/

var count1 = 0; 
var count2 = 0; 
// 1. Get two divs to move on different key presses; 
    $(function(){ 
    $(document).keydown(function(e){ 
    switch (e.which){ 
     case 39: //lright arrow key 
      count2++; 
     $('.box2').animate({ 
      left: '+=50' 
     }); 
     break; 
     case 90: //z key 
     count1++; 
     $('.box1').animate({ 
      left: '+=50' 
      }); 
     break; 
     } 
    }); 
}); 

// 2. Get one div to move on button click; 
$(function(){ 
$('#start').click(function() { 
    alert('Chug that Duff!'); 
    var rabbit = $(".rabbit"); 
    rabbit.animate({left: '+=100%'}, 'slow'); 
    }); 
}); 
$(function(){ 
    var winPos = $('#background').width(); 
    if (winPos/50 > count1) 
    alert('Homer Wins!'); 
    else if (winPos/50 > count2) 
    alert('Barney Wins!'); 
}); 

答えて

1

ただ、アニメーションに条件を追加します。

var maxLeft = $(window).width() - $('.box1').width(); 

// If the box's x-position is less than the max allowed, then animate 
if ($('.box1').position().left < maxLeft) { 
    $('.box1').animate({ 
     left: '+=50' 
    }); 
} 

値(ウィンドウ幅 - ボックスの幅)は箱がになる点です画面の最後。あなたの代わりにこのような何かをすることができて、あなたのステップサイズは、(それは例えば、おそらく50で割り切れない)現在のウィンドウサイズに応じて、画面の終わりを越え箱を取ることに注意してください:

var stepSize = 50; 
var maxLeft = $(window).width() - $('.box1').width(); 

// If the box's x-position is less than the max allowed, then animate 
if ($('.box1').position().left < maxLeft) { 
    var diff = maxLeft - $('.box1').position().left; 

    // If the next step would take the box partially off the screen 
    if (diff < stepSize) { 
     $('.box1').animate({ 
      left: '+=' + diff 
     }); 
    } else { 
     $('.box1').animate({ 
      left: '+=' + stepSize 
     }); 
    } 
} 

編集:がここ三項演算子使用して短いバージョンです:

var stepSize = 50; 
var maxLeft = $(window).width() - $('.box1').width(); 

// If the box's x-position is less than the max allowed, then animate 
if ($('.box1').position().left < maxLeft) { 
    var diff = maxLeft - $('.box1').position().left; 

    $('.box1').animate({ 
     left: '+=' + (diff < stepSize ? diff : stepSize) 
    }); 
} 
+0

は、うーん、私は「左」ということになっていますがこれは私のために意図したとおりに動作し、私はあなたが左に見ているすべてのエラーを、届かない – Vidro3

+0

定義されていません定義されていませんか? –

+0

2番目の例では、最初のインスタンスになっていました。あなたはJSのどこにこれを置いていますか? 次にswitchステートメントの各ケース内のifステートメントを追加しました。 – Vidro3

関連する問題