第一阶段,试用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);
});
Stellungnahme:Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn