在背景图像完成加载时调用函数 [英] Calling a function when the background image finishes loading

查看:64
本文介绍了在背景图像完成加载时调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在加载远程文件作为背景图片,最多可能需要2秒钟,具体取决于互联网连接。

I am loading a remote file as a background image, and it could take up to 2 seconds, depending on the internet connection.

我想在背景图片完成加载时触发一个函数。

I would like to trigger a function when the background image completes loading.

它会像这样工作(虽然这显然没有)

It would work something like this (although this obviously does not)


$("body").css("background image","url('very_big_remote_image')",
         function(data){alert("done")}
         );



推荐答案

试试这个,基本上我加载一个图像对象并将其源设置为背景。一旦加载我改变背景并触发回调:

Try this, basically I load an image object and set its source to the background. Once it has loaded I change the background and fire the callback:

var img = new Image();
img.onload = function() {
    $("body").addClass("bg");
    //the callback function call here
};
img.src = 'very_big_remote_image';

此图片从不显示,只是强制浏览器加载它然后缓存它。

This image is never shown, just forces browser to load it then it is cached.

然后在你的css中有这个:

Then have this in your css:

body.bg {
    /* change the position or repeat or whatever else you need in this line */
    background: url('/path/to/the/image/above.jpg') no-repeat 0 0 transparent;
}

这篇关于在背景图像完成加载时调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆