首页 > 解决方案 > 使用 jQuery 动画对象。如何在 HTML 中使用淡入、动画和淡出三种技术

问题描述

这是我的 HTML 代码:

$(document).ready(function() {
  var img = $('#img');
  $("#start").click(function() {
    img.fadeIn(1000, function() {
      img.animate({
        left: $(window).width() - 400
      }, 3000, function() {
        img.animate({
          left: '0px'
        }, 3000, function() {
          img.fadeOut(1000);
        })
      });
    });
  });
});
.img {
  width: 400px;
  height: 100px;
  /* background-color: red; */
  position: absolute;
  top: 50px;
  left: 0;
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="start">Start</button>
<div>
  <img id="img" src="guy-walking.gif" width="400" />
</div>

我怎样才能把那个家伙(gif)转过来,让他穿过屏幕向前走?当这个人回到起点时,即从右到左,看起来他是月亮倒退。我不能把他转过来让他往回走。请帮忙!!!

标签: jqueryhtmlcss

解决方案


您可以使用 CSS 的scaleX属性来翻转图像。

transform: scaleX(-1);

在下面的示例中,我创建了一个名为“back”的类,并且在需要翻转动画时添加该类。

请记住,在我的示例中,我的 gif 动画是从右向左走的。这就是为什么我从一开始就翻转图像并在它到达右侧时“取消翻转”它。如果您的动画是从左到右,则必须交换 scaleX 属性。

$(document).ready(function() {
  var img = $('#img');
  $("#start").click(function() {
    img.fadeIn(1000, function() {
      img.animate({
        left: $(window).width() - 400
      }, 3000, function() {
      	img.addClass('back');
        img.animate({
          left: '0px'
        }, 3000, function() {
          img.fadeOut(1000);
        })
      });
    });
  });
});
#img {
  width: 400px;
  height: 400px;
  position: absolute;
  top: 50px;
  left: 0;
  display: none;
  -webkit-transform: scaleX(-1);
  transform: scaleX(-1);
}

#img.back {
  -webkit-transform: scaleX(1);
  transform: scaleX(1);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="start">Start</button>
<div >
  <img id="img" src="https://media0.giphy.com/media/XGnWMiVXL87Xa/source.gif" width="400" />
</div>


推荐阅读