jQuery Detect Image Load
I'm building a website using jQuery Mobile, and I'm having trouble manipulating the images correctly.
First, here's the address. The images in question are on any of the Websites and Graphics links.
In my CSS, I make images expand to the size of the screen:
img.size{
width: 95%;
padding: 1.5% 1.8% 3% 2.3%;
background-image: url("../images/content/img-bg.png");
background-size: 100%;
}
Unfortunately, before the image loads the height is 0px but the pad开发者_如何学Pythonding still shows up, so I only see the ugly top portion of my background until the image loads to cover it.
I should be able to either hide the image, set the background image to none, or set the padding to 0px until the image loads, then change it with jQuery, but (I think because the images are loaded via Ajax after the full page has loaded) jQuery isn't seeing that the images have loaded. For instance, this will make all the images hidden, so the images are being detected:
$('img').css('visibility', 'hidden');
But this will not work, even if I remove the above line of code and have the CSS hide the images by defualt
so in the CSS:
img{
visibility: hidden;
}
and in the code:
$('img').load(function() {
$('img').css('visibility', 'visible');
});
or
$('img').complete(function() {
$('img').css('visibility', 'visible');
});
Any ideas as to how to get jQuery to really detect if my images have loaded? Even a pure CSS solution would be fine, but I'd still like to know what jQuery's issue is.
Thanks.
p.s. I can add a CSS height in px or em, but
height: 95%;
doesn't work. I realize percentage heights generally do not work, but since the image width changes with the screen, the height needs to as well, so setting no height forces the CSS to constrain the proportions.
Depending of the browser, $('img')
.complete seems to work better than load()
Here's a script I did for an heavy photo gallery:
First, you'll have to hide the container of the images, or put a layer over it in some way... anything to hide the loading for the visitor.
countImgs = $("#container > img").size();
imgsLoaded = 0;
$("#container > img").each( function() {
if(this.complete) {
imgsLoaded++;
} else {
$(this).load( function() {
imgsLoaded++;
});
}
});
Then, do some function with setTimeout
to test if imgsLoaded==compteImgs
.
精彩评论