【问题标题】:Click image to animate (move) to the right单击图像以动画(移动)到右侧
【发布时间】:2017-11-02 19:21:23
【问题描述】:

尝试使用 animate() 方法在单击图像时将图像向右移动 250 像素,但失败了。

我可以使用按钮完成此操作,但是在将图像用作“按钮”时会遇到困难。

HTML

<div class="runner-animation"> 
    <h1> Click to see how fast the runner moves! </h1>
    <img src="Images/runner-clip-art.png" id="runner">
</div>

jQuery

$(document).ready(function(){
$("#runner").click(function(){
    $("#runner").animate({right: '250px'});
});

任何帮助将不胜感激。

干杯

【问题讨论】:

  • 图片的css位置属性是否设置为固定/相对/绝对?
  • 请提供任何 jsfiddle
  • @Taplar 还没有 CSS,没有。
  • 试试看。没有位置的 IIRC,上/下/左/右被忽略
  • @Taplar 是 IIRC 引导程序吗?我只想使用 jQuery。

标签: jquery html jquery-animate


【解决方案1】:

只要您定位了图像,纯 jQuery 就可以正常工作。

也就是说,您的代码中缺少右括号和括号...

编辑:您想知道如何在动画运行后重置动画。下面的代码做了一些改动:首先,动画包含一些额外的参数——一个时间和一个在动画完成时运行的函数。在这个函数中,我隐藏了 h1 标签,并显示了一个重置​​按钮。重置按钮的代码只是将图像恢复到其原始 CSS 位置,隐藏重置按钮并重新显示 H1 标签。

希望这会有所帮助!

$(document).ready(function() {
  $("#runner").click(function() {
    $("#runner").animate({
      left: '250px'
    }, 200, function(){ 
      // When animation is complete, display the reset button.
      $('h1').hide();
      $('.reset').show()
    });
  });
  
  $(".reset").on("click", function(){
    $('h1').show();
    $(this).hide();
    $("#runner").css('left', '0px');
  });
});
#runner {
  position: relative;
}

.reset {
 display:none;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="runner-animation">
  <h1> Click to see how fast the runner moves! </h1>
  <p><button class="reset">Reset my runner!</button></p>
  <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRi-GA_UEaos9P4H5dWe31rt-00En4KB6sE3RydFX91WGXKMpz1" id="runner">
</div>

【讨论】:

  • 这太完美了,谢谢。你知道我如何通过点击来重置动画以返回开始吗?
  • @KaliMa 我已经编辑了上面的代码来做到这一点。祝你好运!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-05
  • 2013-11-05
  • 2019-04-10
  • 2022-11-17
  • 2017-01-06
  • 2016-03-02
相关资源
最近更新 更多