jQuery img src改变不是立竿见影的

时间:2013-07-19 18:35:12

标签: jquery image src

我在简单的图库中使用jQuery。图像fadeOut,src改变,并且它们淡入。

以前的图像经常褪色;只有元素达到完全不透明度才会显示新图像。

什么可能导致延迟并随后跳转到新图像?

HTML

<div id="slide">
    <img src="/img/products/image1.jpg">
</div>

JS

var index = 0;

$(function() {
    if (srcs.length > 1) {
        setInterval("slide(800, 800)", 6000);
    }
});

function slide(o,i) {
    index++;
    if (index == srcs.length) index = 0;
    $("#slide img").fadeOut(o, function() {
        $(this).attr("src", path + srcs[index] + ext);
        $(this).fadeIn(i);
    });
}

修改:我将fadeIn()放入fadeOut()的回调中,但现在问题明显发生次。图像一直淡出,然后一直淡入,然后改变。

this answer中的

解决方案.each()功能在新图片fadeIn()期间导致轻微闪烁,但完全删除了.each()部分修好了。

3 个答案:

答案 0 :(得分:1)

这是因为javascript不会等待fadeOut完成后再继续使用代码使用这样的东西

    $('#slide img')
         .fadeOut(o, function(){
              $(this).attr('src', path + srcs[index] + ext);
              $('#slide img').fadeIn(i);
         });

它应该等到fadeOut完成后再启动fadeIn。

答案 1 :(得分:1)

我建议添加fadeIn函数作为fadeOut的回调函数。这样就可以确保在加载新图像之前完成-out动画。

请参阅文档:http://api.jquery.com/fadeOut/

$('#slide img').fadeOut(o, function() {
    // Animation complete.
    // Do fadeIn function here
});

答案 2 :(得分:1)

您可以在预加载功能上尝试这样的事情:

$.each(imgArray, function() {
    var i = new Image();
    i.src = path + this + ext;
});

取代ajax调用,并在幻灯片函数上尝试此操作:

$('#slide img').fadeOut(o, function(){
    var that = this;
    this.src = path + srcs[index] + ext;
    this.onload = function() {
        $(that).fadeIn(i);
    };
});