我正在尝试在加载空div后在我的菜单栏中淡入淡出(空div中有一个大的背景图像)。该图像需要一两秒才能加载,所以我需要在加载图像(div)后淡入菜单。
这是我的jquery:
$(.top-bg).ready(function() {
$(".top-bar").fadeIn(1000);
});
(文件.ready没有给出正确的效果。)
答案 0 :(得分:1)
你不能等到直接附加到div的加载事件:你应该在domready
事件加载图像,然后淡化div本身。还要考虑您应该检查图像是否处于complete
状态(如果它已经被缓存)
尝试类似
的内容$(function() { // on dom ready event
var div = $(".top-bar"),
src = "url-to-your-image",
tmp = $('<img />');
tmp.one('load', function() { div.fadeIn(1000) }) /* one: it need to be
executed one time only */
.attr('src', src);
if (tmp.get(0).complete) {
tmp.trigger('load');
}
});
答案 1 :(得分:1)
您不能直接在div
上执行此操作。
相反,创建一个内存中的图像元素,并将其源设置为背景图像的来源;
然后你可以将你的函数附加到img
的加载事件:
$(document).ready(function($) {
var img = new Image();
img.src = $('.top-bg').css('background-image').replace(/url\(|\)/g, '');
img.onload = function(){
$(".top-bar").fadeIn(1000);
};
});
答案 2 :(得分:1)
试试这个:
$(document).ready(function($) {
var tmp = $('<img src="relative_path_to_image" />');
tmp.load(function() {
$(".top-bar").fadeIn(1000);
tmp.remove();
});
});