如何在jQuery中为边界内的图像设置动画

时间:2014-03-20 01:14:00

标签: javascript jquery html css

我正在尝试在矩形边界内使用jQuery为图像设置动画,但我的代码并不限制图像移动的距离。如何修改我的代码以限制图像仅在200px×300px的框内移动?

的index.html

  <img class="pic" src="panda.jpg"/>

的style.css

  .pic {
        position: relative;
        left: 0;
        top: 0;
        margin-left: 355px; 
        margin-top: -180px;
      }

的jQuery

  $(document).keydown(function(key) {
  switch(parseInt(key.which,10)) {
  case 37:
  $('.pic').animate({left: "-=10px"}, 'fast');
  break;
  case 38:
  $('.pic').animate({top: "-=10px"}, 'fast');
  break;
  case 39:
  $('.pic').animate({left: "+=10px"}, 'fast');
  break;
  case 40:
  $('.pic').animate({top: "+=10px"}, 'fast');
  break;
    }
 });

jsfiddle demo:http://jsfiddle.net/waAK2/

3 个答案:

答案 0 :(得分:1)

您必须设定自己的界限和限制。

修改

注意我在这里使用了margn-left和margin-top。确保在css中设置支架和.pic的宽度和高度。使MovementSpeed可编辑。

var movementSpeed = 10;

var leftMarginLimit = parseInt($('.pic').parent().css('width')) - parseInt($('.pic').css('width'));
var topMarginLimit = parseInt($('.pic').parent().css('height')) - parseInt($('.pic').css('height'));

var leftMargin = parseInt($('.pic').css('margin-left'));
var topMargin = parseInt($('.pic').css('margin-top'));

$(document).keydown(function(key) {

    // LEFT
    if (key.which == 37)
    {
        leftMargin -=movementSpeed;
        if (leftMargin < 0){leftMargin = 0;}
        if (leftMargin > leftMarginLimit){leftMargin = leftMarginLimit;}
        $('.pic').animate({'margin-left': leftMargin+'px'}, 'fast');
    }

    // RIGHT
    if (key.which == 39)
    {
        leftMargin +=movementSpeed;
        if (leftMargin < 0){leftMargin = 0;}
        if (leftMargin > leftMarginLimit){leftMargin = leftMarginLimit;}
        $('.pic').animate({'margin-left': leftMargin+'px'}, 'fast');
    }

    // UP
    if (key.which == 38)
    {
        topMargin -=movementSpeed;
        if (topMargin < 0){topMargin = 0;}
        if (topMargin > topMarginLimit){topMargin = topMarginLimit;}
        $('.pic').animate({'margin-top': topMargin+'px'}, 'fast');
    }

    // DOWN
    if (key.which == 40)
    {
        topMargin +=movementSpeed;
        if (topMargin < 0){topMargin = 0;}
        if (topMargin > topMarginLimit){topMargin = topMarginLimit;}
        $('.pic').animate({'margin-top': topMargin+'px'}, 'fast');
    }
});

而不是动画,你应该尝试

$('.pic').css({'margin-left': leftMargin+'px'});

感觉反应更快,否则你必须等待动画完成等等。

答案 1 :(得分:1)

嘿,只是为你的盒子做了一个小提琴,检查所有角落......只需要放入一些条件让它停下来。

这些方面的东西:

if ($('.pic').css("left") >= "10") {
    $('.pic').animate({
        left: "-=10px"
        }, 'fast');
    }

http://jsfiddle.net/descene/waAK2/2/

答案 2 :(得分:0)

放置一个位置为相对的容器。该元素中的子元素(绝对位置)的任何动画都将保留在内部,并且您可以检查步骤函数中的元素边界,以防止它移出边界。

fiddle将在每个动画期间打印属性。您可以检查并处理其中的任何逻辑。

$('#child-1').animate({
    left: 10,
    top: 100
}, {
    duration: 3000,
    step: function(now, fx){
        console.log(now, fx);
    }
})