jQuery Animate左右只发生一次

时间:2016-09-28 18:26:53

标签: javascript jquery jquery-animate

我正试图在我网站的旋转木马上制作一些内容,以便根据按下的按钮向左或向右移动。这是我的示例代码:

HTML

<div class="red-bg">
  <div class="blue-bg" id="toAnimate">
    <p>Some text</p>
    <p>Some other text</p>
    <button id="leftButton">left</button>
    <button id="rightButton">right</button>
  </div>
</div>

CSS

.red-bg {
  background: red;
  height: 250px;
  margin-left: 300px;
  padding: 20px;
  width: 250px;
}

.blue-bg {
  background: blue;
  position: relative;
}

JS

$(document).ready(function() {

  function animateLeft() {
    $("#toAnimate").animate({
      opacity: 0,
      right: 100
    }, 500, function() {
      $('#toAnimate').css('right', '0');
      $('#toAnimate').css('opacity', '1');
    });
  }

  function animateRight() {
    $("#toAnimate").animate({
      opacity: 0,
      left: 100
    }, 500, function() {
      $('#toAnimate').css('left', '0');
      $('#toAnimate').css('opacity', '1');
    });
  }

  $('#leftButton').click(function() {
    animateLeft();
  });

  $('#rightButton').click(function() {
    animateRight();
  });

});

以下是我的CodePen的链接:http://codepen.io/leofontes/pen/NRgOxb

基本上,我的情况是,如果我先按左侧按钮,它会起作用并向左侧动画,但是如果我按右侧左侧停止工作,只会淡出,但不会向左移动(右边仍然有效)。

有关为什么会发生此行为或如何解决此问题的任何想法?谢谢! 如果需要更多信息,请告诉我

1 个答案:

答案 0 :(得分:1)

<强>问题: 在你的代码中,你尝试从右到左100px并从左到右

  

首先,删除元素中的左侧样式或执行此操作

<强> HTML

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
<script src="https://code.jquery.com/jquery-2.0.3.js"></script>

</head>
<body>
    <div class="red-bg">
      <div class="blue-bg" id="toAnimate">
        <p>Some text</p>
        <p>Some other text</p>
        <button id="leftButton">left</button>
        <button id="rightButton">right</button>
      </div>
    </div>
</body>
</html>

JAVA SCRIPT

$(document).ready(function() {

  function animateLeft() {
    $("#toAnimate").animate({
      opacity: 0,
      left: -100
    }, 500, function() {
      $('#toAnimate').css('left', '0');
      $('#toAnimate').css('opacity', '1');
    });
  }

  function animateRight() {
    $("#toAnimate").animate({
      opacity: 0,
      left: 100
    }, 500, function() {
      $('#toAnimate').css('left', '0');
      $('#toAnimate').css('opacity', '1');
    });
  }

  $('#leftButton').click(function() {
    animateLeft();
  });

  $('#rightButton').click(function() {
    animateRight();
  });


});
相关问题