1

感谢您抽出一些时间。

我想知道是否有一种可能的方法使用 jQuery 在 div 背景图像完成下载和渲染后立即触发函数。

假设你有这个 div

<div id="img1" class="img1"> </div>

img1 样式在哪里

.img1 {
    background-image: some_big_image.png;
    background-position:center;
    background-repeat:no-repeat;
    background-size:cover;  
    display: none;
}

考虑这个 javascript 函数

function showDiv() {
  $("#img1").fadeIn(1000);
}

有没有办法在图像渲染后立即调用上一个函数?通过渲染,我的意思是调整大小以很好地适应它的 div 并准备好显示。

我发现了很多关于在页面加载后或下载图像后触发功能的信息,但没有关于后渲染的信息。

你们是最棒的。先感谢您。

4

2 回答 2

2

Try

var img = new Image();
img.src = "/some_big_image.png";
img.onload = function( ) {
    $("#img1").css("background-image", "url('" + img.src + "')" ).fadeIn(1000);
}

Fiddle here

于 2012-11-28T13:17:03.973 回答
0

I know you already accepted an answer above, but this can be simplified grealy to just use the jquery magic function

$(function() {
    $("#img1").fadeIn(1000);
}

You replied above that the onload event wasn't working for you. The $(function() { //code here } ); fires when the dom is completely ready (not sure if all browsers do this by default for the onload event), so perhaps that is why you were having issues. It is also handy because you can call it multiple places on your page and they will be combined (rather then directly setting onload, which will be overriden if its set somewhere else)

Fiddle here: http://jsfiddle.net/5cR4G/8/

于 2012-11-28T13:17:07.803 回答