2013-07-02 195 views
2

我有一个容器,持有3个标签,当点击一个标签,容器得到一个新的类 - 当它获得类,它改变了CSS中的backgroundImage,它改变了在标签容器中的内容 - 我的问题是背景图像它相当沉重,它的PNG文件,因为我需要的透明度,所以我不能将它们更改为JPG的左右...jquery负载预加载背景图像

所以我想知道如果有是一种方式,我可以预先加载背景图像,然后更改tab容器中的内容,也许使用.load()函数或类似的东西?我到目前为止的脚本是:

$(".tabs-content div.tabpage").hide(); // Initially hide all content 
$(".tabs li:first").attr("id", "current"); // Activate first tab 
$(".tabs-content div:first").fadeIn(); // Show first tab content 
$('.tab-container a').click(function(e) { //If only tabs, change to .tabs a 
    e.preventDefault(); 
    var className = $(this).attr("name") 
    $(document).find(".tab-container").attr("class", "grid_9 tab-container " + className); 
    if ($(this).closest("li").attr("id") == "current") { //detection for current tab 
     return 
    } else { 
     $(".tabs-content div.tabpage").hide(); //Hide all content 
     $(".tabs li").attr("id", ""); //Reset id's 
     $(this).parent().attr("id", "current"); // Activate this 
     $('#' + $(this).attr('name')).fadeIn(); // Show content for current tab 
    } 
}); 
+1

检查此http://stackoverflow.com/questions/476679/preloading-images-with-jquery,它不必作为背景图像预加载。预加载它,然后将它作为背景图片应用会很好。只需将它们预加载到任何功能之外,便可立即进行预加载。 – smerny

+0

呃,在那里有一千个答案:)哪一个是正确的? :) – nuffsaid

+0

他们中的大多数人可能会工作,尝试与票最多的人。 – smerny

回答

0

这可能是最简单的方法可以让你预载的图片:

$.fn.loadImages = function() { 
    this.each(function(){ 
     $('<img/>')[0].src = this; 
    }); 
} 

$.loadImages(['your-image.png','your-image2.png','your-image3.png']); 

如果还是不行,请尝试加载它们像jquery.load内:

$.fn.loadImages = function() { 
    this.each(function(){ 
     $('<img/>')[0].src = this; 
    }); 
} 

$(window).load(function(){ 
     $.loadImages(['your-image.png','your-image2.png','your-image3.png']); 
}); 
1

$( 'IMG')ATTR;( “SRC”, “URL这里 !”)

0

您可以加载一个隐藏的图像,并在图像加载完成后进行更改,请检查此questionanswer,我想避免重复它已经在SO中的代码。