2017-07-16 54 views
2

我想學習jquery,我想創建淡入淡出效果,它通過圖像循環。我已經使用setInterval函數來遍歷圖像,但它僅適用於第一次迭代。jquery淡入淡出效果不起作用

$(document).ready(function() { 
 
     var newcount = 0; 
 
     var image = $(".image-store img"); 
 
     image.hide(); 
 
     var image_array = []; 
 
     image.each(function() { 
 
     image_array.push($(this).attr('src')); 
 
     }); 
 
     var showimg = $(".image-disp img"); 
 
     showimg.attr("src", image_array[newcount]); 
 

 
     setInterval(function() { 
 
     showimg.fadeOut(2000, function() { 
 
      newcount = newcount + 1; 
 
      showimg.attr("src", image_array[newcount]); 
 
      showimg.fadeIn(2000); 
 
     }); 
 
     if (newcount == image_array.length) { 
 
      newcount = -1; 
 
     } 
 
     }, 3000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="image-store"> 
 
    <img src="img/img1.jpg"> 
 
    <img src="img/img2.jpg"> 
 
    <img src="img/img3.jpg"> 
 
</div> 
 
<div class="image-disp"> 
 
    <img src=""> 
 
</div>

回答

2

它的工作原理,但你的代碼的末尾缺少});。使用瀏覽器控制檯來了解是否有任何錯誤。

1

$(document).ready(function() { 
 
    var newcount = 0; 
 
    var image = $(".image-store img"); 
 
    image.hide(); 
 
    var image_array = []; 
 
    image.each(function() { 
 
    image_array.push($(this).attr('src')); 
 
    }); 
 
    var showimg = $(".image-disp img"); 
 
    showimg.attr("src", image_array[newcount]); 
 

 
    setInterval(function() { 
 
    showimg.fadeOut(2000, function() { 
 
     newcount = newcount + 1; 
 
     showimg.attr("src", image_array[newcount]); 
 
     showimg.fadeIn(2000); 
 
    }); 
 
    if (newcount == image_array.length) { 
 
     newcount = -1; 
 
    } 
 
    }, 3000); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="image-store"> 
 
    <img width="50" src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"> 
 
    <img src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"> 
 
    <img width="50" src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"> 
 
</div> 
 
<div class="image-disp"> 
 
    <img width="200" src=""> 
 
</div>