jQuery plugin vertical align images setTimeout
I have created a quick and simple plugin that vertical aligns images that I have used successfully in a number of websites although I am now working with a new CMS that automatically resizes the images which creates a delay in loading the resized images thus causing the plugin to return null for the height. This only happens on first load of the page.
I thought I could fix this with a timeout although this causes the parent.height to always return null.
//Vertically Allign Images
jQuery.fn.vAlign = function() {
return this.each(function(){
setTimeout(function(){
var $strip = jQuery(this);
var ah = $strip.height();
var ph = $strip.parent().height();
a开发者_开发百科lert('height = '+ah+' parent = '+ph);
//height = 429 parent = null
var mh = Math.ceil((ph-ah) / 2);
$strip.css('margin-top', mh);
},1000);
});
};
Inside the setTimeout function, this
is the window
object (the setTimeout function runs in global scope), and so $(this).parent()
is an empty jQuery object (because window
has no parent).
It would be best if you can load the images using JavaScript so that you can assign a load
event handler to do the vertical alignment, something like:
jQuery.fn.vAlign = function () {
return this.bind('load', function () {
// do alignment
});
};
$('<img />')
.vAlign() // call before assigning src
.appendTo('body')
.attr('src', '...');
I believe you lose the context of the jQuery function when you fire setTimeout. Try defining your variables in the global scope and then calling setTimeout
.
Either way, this doesn't seem to me to be the best way to vertically align images -- is there a reason you're doing this with JS rather than using the line-height
or vertical-align
CSS properties?
精彩评论