繁体   English   中英

jQuery加载以预加载背景图像

[英]jquery load for preloading background images

我有一个容器,其中包含3个选项卡,单击一个选项卡时,该容器将获得一个新类-当获取该类时,它将更改CSS中的backgroundImage,并更改选项卡容器中的Content-我的问题是因为我需要透明性,所以背景图像相当重,而且是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
    }
});

$('IMG')。attr(“ src”,“ URL在这里!”);

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

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

这将加载图像。 此处提供更多信息(但我自己尚未检查文章的内容): http : //perishablepress.com/3-ways-preload-images-css-javascript-ajax/

这可能是您预加载图像的最简单方法:

$.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']);
});

您可以加载隐藏的图像,并在图像完成加载后进行更改,请检查此问题答案 ,我希望避免重复代码,因为它已经存在于SO中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM