JQuery slideshow的一個小問題(如何發現及解決過程)

來源:互聯網
上載者:User

第一階段,試用slideshow
在做一個網頁homepage的時候,想用slideshow[1]做圖片轉場效果,其中js部分代碼如下:
複製代碼 代碼如下:
function next_slide() {
  var $active = $('#bitware-overlay img.active');
  if ($active.length == 0)
    $active = $('#bitware-overlay img:last');
  var $next = $active.next().length ? $active.next() : $('#bitware-overlay img:first');
  $active.addClass('last-active');
  $next.addClass('active');
  $next.css({opacity: 0.0});
  $next.animate({opacity: 1.0}, 1500,function(){
    $active.removeClass();
  });
}
$(function() {
  setInterval("next_slide()", 4000);
});

第二階段,發現問題
在開啟頁面所以的正常測試都沒問題,最後領導發現,當瀏覽器同時開啟多個tab,停留他tab中的頁面一段時間後,會出現圖片是最後一張圖片,然後變化為第一張圖片,剛變化(有淡入的的效果)完成,就突然跳轉到最後一張圖片。當我改為:
複製代碼 代碼如下:
function next_slide() {
  var $active = $('#bitware-overlay img.active');
  if ($active.length == 0)
    $active = $('#bitware-overlay img:last');
  var $next = $active.next().length ? $active.next() : $('#bitware-overlay img:first');
  $active.addClass('last-active');
  $next.addClass('active');
  $next.css({opacity: 0.0});
  $next.animate({opacity: 1.0}, 1500);
  $active.removeClass();
  setTimeout("next_slide()", 4000);
}
$(function() {
  setTimeout("next_slide()", 4000);
});

發現停留在其它tab後,回到頁面時,圖片顯示的順序正確,間隔時間也正確,4000毫秒,但是顯示出來的時候,是直接跳轉式,也不是淡出形狀,似乎animate的1500毫秒沒有啟動任何效果。過一段時間會恢複正常,但是這種現象的時間長短,跟停留在別的tab時間長短似乎成正比。
第三階段,解決問題
最後發現原因,是因為jquery的本質是單線程[2],當停留在別的tab中,任務中將next_silde()函數積壓過多所致。最後找到的解決方案[4]如下:
複製代碼 代碼如下:
function next_slide() {
  var $active = $('#bitware-overlay img.active');
  if ($active.length == 0)
    $active = $('#bitware-overlay img:last');
  var $next = $active.next().length ? $active.next() : $('#bitware-overlay img:first');
  $active.addClass('last-active');
  $next.addClass('active');
  $next.css({opacity: 0.0});
  $next.animate({opacity: 1.0}, 1500,function(){
  $active.removeClass();
    setTimeout("next_slide()", 4000);
  });
}
$(function() {
  setTimeout("next_slide()", 4000);
});

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.