在页面上的某个位置停止动画[jQuery]

时间:2016-10-02 03:11:48

标签: javascript jquery animation scroll

我有一个div在keydown事件监听器上移动页面。我试图找到一种方法让它在一定数量的keydowns(通过步骤*点击>屏幕大小计算)后或当动画div到达屏幕的末尾时停止,我想这需要响应屏幕大小。

目前,animate继续在keydown上触发,div将向外滚动。

此示例是此页面上的第二个演示:http://api.jquery.com/animate/ 您可以单击向左或向右,直到块移出视图。我怎么把它包含在容器中?呃,容器?

这里是我的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 个答案:

答案 0 :(得分: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)
    });
}