用于预加载背景图像的jquery加载

时间:2013-07-02 12:14:07

标签: javascript jquery

我有一个容器,拿着3个标签,当点击一个标签时,容器会获得一个新类 - 当它获得类时,它会更改CSS中的backgroundImage,并更改选项卡容器中的内容 - 我的问题是背景图像相当沉重,而且它是PNG文件,因为我需要透明度,所以我不能将它们改为JPG左右...

所以我想知道是否有一种方法,我可以预先加载背景图像,然后更改选项卡容器中的内容,可能使用.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
    }
});

4 个答案:

答案 0 :(得分:1)

$('IMG')。attr(“src”,“URL here!     “);

答案 1 :(得分:0)

您可以使用JavaScript Image对象。像这样:

var img = new Image();
img.src = "http://yourserver/yourimage";

这将加载图像。这里有更多信息(但我自己没有查看过该文章的内容):http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/

答案 2 :(得分: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']);
});

答案 3 :(得分:0)

您可以加载隐藏的图片并在图片完成加载时更改它,请检查questionanswer,我希望避免复制它已经在SO中的代码。

相关问题