jQuery - If image width is less than 75px add 1/2 the difference as padding?
With jQuery how can I see if a div is less than 75px, and if it is add 1/2 (half) the difference as left padding?
So if an image is 75px or bigger, then nothing happens, but if it's 71px then 2px of left-padding is applied.
Note, the size is defined by CSS, the actual images are bigger.
Thanks
The following didn't work for me:
$(window).load(function() {
$(function(){
var img= $('#views_slideshow_singleframe_pager_product_slideshow-node_content_1 .pager-item img');
if(img.width() <开发者_如何学Python75)
{
img.css("padding-left", (img.width() -75)/2);
});
});
UPDATE - I need to target several images on a page with this.
UPDATE - I'm adding the code suggestions locally so you cant see it live, but a non-js version of the site is here: link - click on one of the thumbnails under the 'SIZE' drop down box to see a thumbnail that's too small. This version is a little out of date so I'll come back with a newer one as soon as its uploaded. Thanks
UPDATE - the thumbnail images are themselves generated by javascript, so the code needs to be run after they're created. I've used window load for this reason.
Try this jQuery, I'm not sure how bug-proof it is, though:
$('img').live('click', function() {
$.each($('img'), function() {
var image = $(this);
if (image.width() < 75) {
image.css('padding-left', ((75 - image.width()) / 2));
}
});
});
EDIT : This code will fire each time any image is clicked. You can make this more specific by using a selector to find clicked images within a certain container, such as a "div".
I hope it helps, though,
spryno724
From your question I can't tell if you want to determine the div width or the image width so this should work for finding the width of anything (just change 'img' to whatever you want to add the padding to) and then adding the needed value to the left-padding.
$('img').each(function(){
$self = $(this).width();
if($self < 75){
var diff = (75 - $self) / 2;
$(this).css("padding-left", diff);
}
});
Update (the above would work for something like a div... but not an image):
In the browser I am using (webkit) the width of the image is not set when jQuery asks for it. This results in the width being 0 so the code takes 75, divides by 2 and then you get 37.5 added every time.
This should work (uses the image's onload event):
var the_width, the_diff;
$('img').each(function(){
var img = $(this);
$("<img/>").attr("src", $(img).attr("src")).load(function(){
the_width = this.width;
if(the_width < 75) {
the_diff = (75 - the_width) / 2;
img.css("padding-left", the_diff);
}
});
});
精彩评论