不同浏览器中的无限js循环

Infinite js loop in different browsers

本文关键字:无限 js 循环 浏览器      更新时间:2023-09-26

我正在尝试用jQuery制作一个无限旋转的imagereel。该图像级别以5000毫秒的间隔在图像之间切换,然后淡出"旧"图像并淡入"新"图像。要显示的图像有一个style-attribute为"display:inline"。

代码如下:

function switchImage(){
    var selector = $('#fotoreel img[style="display: inline; "]');
    var nextOne = $(selector).next();
    if($(nextOne).length == 0)
    {
        var nextOne = $('#fotoreel img:first');
    }
    $(selector).fadeOut('normal',function(){
        $(nextOne).fadeIn('normal');
    });
    var t = setTimeout("switchImage()",5000);
}
$(document).ready(function(){
    setTimeout("switchImage()",5000);
});

问题是它在Chrome中工作得很好,但在Firefox和Opera中它只移动图像一次。在IE中情况更糟;这里它根本不起作用。

你们知道用javascript无限循环更好的方法吗?现在我使用setTimeout()再次调用该函数,但这似乎不起作用。

编辑

好的,谢谢大家!这么快的反应,太棒了!

我使用的解决方案是添加一个类并搜索它,而不是搜索样式。display:inline似乎并不是一个问题,但所有浏览器似乎都以不同的方式实现了jQuery的fadeIn()函数。

我也就是想在"display: inline;"上精确过滤,因为空格是在Chrome中添加的,而不是在IE, FF或Opera中添加的。因此,这意味着style属性根本不能准确地进行过滤。愚蠢的我!:)

我确保一个类被添加到当前显示的图像中,并通过过滤该类找到下一个。现在它就像一个魅力。

谢谢大家的回答,我爱这个地方!: D

这很可能是因为您正在检查style属性,这在浏览器中非常不一致。I.E.根本不起作用,或者与各种数量的空白一起工作。只需简化选择器,使用类或":visible"

如果用class显式标记图像,效果可能会更好:

function switchImage(){
  var selector = $('#fotoreel img.current');
  var nextOne = $(selector).length ? $(selector).next();
  if($(nextOne).length == 0)
  {
    var nextOne = $('#fotoreel img:first');
  }
  $(selector).fadeOut('normal',function() {
    $(selector).removeClass('current');
    $(nextOne).addClass('current').fadeIn('normal');
  });
  setTimeout(switchImage, 5000);
}
$(document).ready(function(){
  $('#fortoreel img:last-child').addClass('current');
  setTimeout(switchImage,5000);
});

还请注意,在我调用"setTimeout()"我传递了对函数的直接引用,而不是调用它的字符串版本的代码。

这不起作用,因为您提到的浏览器不喜欢您使用的display: inline选择器。

我使用下面的命令使它工作:

function switchImage() {
    var selector = $('#fotoreel img:visible');
    var nextOne = selector.next();
    if (nextOne.length == 0) {
        var nextOne = $('#fotoreel img:first');
    }
    selector.fadeOut('normal', function () {
        nextOne.fadeIn('normal');
    });
    var t = setTimeout(switchImage, 5000);
}
$(document).ready(function () {
    setTimeout(switchImage, 5000);
});