jQuery动画左和右只发生一次

jQuery Animate Left and Right only happening once

本文关键字:一次 动画 jQuery      更新时间:2023-09-26

我试图在我的网站的旋转木马动画的一些内容,使其向左或向右取决于按下的按钮。这是我的示例代码:

<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

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

任何关于为什么这种行为发生或我如何修复它的想法?谢谢你!如果需要更多信息,请告诉我

问题:在你的代码中你尝试从右到左100px和从左到右

首先,移除元素中的左侧样式,或者像这样

<!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脚本/strong>

$(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();
  });

});