使用jQuery动画图像更改

时间:2018-02-13 07:17:11

标签: javascript jquery html css

我尝试从div中设置img更改动画,我尝试使用jquery这样做,因为它似乎是最干净的方式。我尝试使用this回答但没有任何成功。我的做法错在哪里?

HTML:

 <div class="jumbotron text-center" id="main-jum">
    <img id="jum-img" src = "https://im.whatshot.in/img/2017/Oct/churrosweb-1509092812.jpg">
 </div>


  <div class="container-fluid text-center d-none d-md-block" id="jum-btns">
     <div id="jum-btn" class="btn-group " role="group" aria-label="Basic example">
      <button type="button" id="btn-left" class="btn btn-secondary jum-btn" onclick="changeColor();">Left</button>
      <button type="button" id="btn-middle" class="btn btn-secondary jum-btn" onclick="changeColor();">Middle</button>
      <button type="button" id="btn-right" class="btn btn-secondary jum-btn" onclick="changeColor();">Right</button>
    </div>
  </div>

<script type="text/javascript">
$(document).ready(function(){
  $('#btn-left').click(function() {
   $('#jum-img').fadeOut(500, function() {
       $('#jum-img').attr("src","https://truffle-assets.imgix.net/pxqrocxwsjcc_5pcvIMJdpmi8COGYQ0kua6_churros-with-dulce-de-leche_landscapeThumbnail_en-US.jpeg");
       $('#jum-img').fadeIn(500);
     });
  });
});
</script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

Codepen

2 个答案:

答案 0 :(得分:1)

你正在调用“#jum-Img”,但你的id实际上是“#jum-img”,一旦你将I改为小写,你的代码就可以了。

答案 1 :(得分:0)

这很简单。只需将所有j和脚本放在HTML代码之前。

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $('#btn-left').click(function() {
   $('#jum-img').fadeOut(500, function() {
       $('#jum-img').attr("src","https://truffle-assets.imgix.net/pxqrocxwsjcc_5pcvIMJdpmi8COGYQ0kua6_churros-with-dulce-de-leche_landscapeThumbnail_en-US.jpeg");
       $('#jum-img').fadeIn(500);
     });
  });
});
</script>

<div class="jumbotron text-center" id="main-jum">
    <img id="jum-img" src = "https://im.whatshot.in/img/2017/Oct/churrosweb-1509092812.jpg">
 </div>
  <div class="container-fluid text-center d-none d-md-block" id="jum-btns">
     <div id="jum-btn" class="btn-group " role="group" aria-label="Basic example">
      <button type="button" id="btn-left" class="btn btn-secondary jum-btn" onclick="changeColor();">Left</button>
      <button type="button" id="btn-middle" class="btn btn-secondary jum-btn" onclick="changeColor();">Middle</button>
      <button type="button" id="btn-right" class="btn btn-secondary jum-btn" onclick="changeColor();">Right</button>
    </div>
  </div>