All I have to do is find the image in the center of its parent div.
First off, I tried this.
$(document).ready(function() { $('#image1').css({ 'top': 50%, 'left': 50%, 'margin-top': (-$('#image1').height()/2) + 'px', 'margin-left': (-$('#image1').width()/2) + 'px' }); });
Failed to call $ ('# image1'). height () and width () give 0 before they are fully loaded.
Therefore, I tried to keep track of the size of the image until it had a certain width and height.
as,
function inspectSize() { return ($('#image1').width() != 0); } function setPosition() { if(!inspectSize()) { setTimeout(setPosition, 1000); return; } $('#image1').css({ 'top': 50%, 'left': 50%, 'margin-top': (-$('#image1').height()/2) + 'px', 'margin-left': (-$('#image1').width()/2) + 'px' }); } $(document).ready(setPosition);
However, this does not work.
because $ ('# image'). width () returns 28px before it is loaded in IE8 (by the way, IE7 was great)
So I finally tried the waitForImages jQuery plugin for example
$(document).ready(function() { $('#image1').waitForImages(function() { setPosition();
It works great with cached images, but it doesn't work with non-cached images.
The function is called before Image1 has a width and a height.
What should I do?
source share