垂直和水平移动图像

时间:2018-07-05 10:12:31

标签: jquery html

http://jsfiddle.net/bxkz186y/

有什么方法可以在水平运动期间将那只猫也上下移动20px吗?

我当前的代码:

    $(document).ready(function(e) {
    var width = $(window).width();
    var widthminus = width - 500;
    function goRight() {
        $("#animate").animate({
        left: widthminus
      }, 5000, function() {
         setTimeout(goLeft, 50);
      });
    }
    function goLeft() {
        $("#animate").animate({
        left: 0
      }, 5000, function() {
         setTimeout(goRight, 50);
      });
    }

    setTimeout(goRight, 50);
});

2 个答案:

答案 0 :(得分:1)

使用此代码

它也vertically and horizontally全方位移动图像

$(document).ready(function(e) {
  var width = $(window).width();
  var widthminus = width - 500;

  function goRight() {
    $("#animate").animate({
      left: widthminus
    }, 5000, function() {
      setTimeout(goDown, 50);
    });
  }

  function goDown() {
    $("#animate").animate({
      top: 50
    }, 5000, function() {
      setTimeout(goLeft, 50);
    });
  }

  function goTop() {
    $("#animate").animate({
      top: 0
    }, 5000, function() {
      setTimeout(goRight, 50);
    });
  }

  function goLeft() {
    $("#animate").animate({
      left: 0
    }, 5000, function() {
      setTimeout(goTop, 50);
    });
  }

  setTimeout(goRight, 50);
});

答案 1 :(得分:0)

我认为这是您要寻找的,要双向移动,同时更改left属性和top属性:

$(document).ready(function(e) {
        var width = $(window).width();
        var widthminus = width - 500;
        function goRight_down() {
            $("#animate").animate({
            left: widthminus,
            top:50
          }, 5000, function() {
             setTimeout(goLeft_up, 50);
          });
        }
        function goLeft_up() {
            $("#animate").animate({
            left: 0,
            top:0
          }, 5000, function() {
             setTimeout(goRight_down, 50);
          });
        }

        setTimeout(goRight_down, 50);
    });
.crab {
    height: 400px;
    position: absolute;
    display: block;
    left: 0;
    width: 70px;
    height: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="crab">
 <img src="https://img-aws.ehowcdn.com/600x600p/photos.demandstudios.com/getty/article/165/76/87490163.jpg" id="animate" class="crab" alt="">
</div>