How do i constrain an image to a maximum width/height?
Right now I'm trying the following code. This works most of the time (on a reload, after the 1st visit) but when visiting the page the first time, the image isn't resized properly. I think this is because because the image is loaded before the page ready callback is triggered.
I've tried calling the .resize()
function directly in the .ready()
callback but the image still don't resize on occasion because the image may bot be loaded when the .ready()
callback is triggered.
How should i go about hooking up the resize()
function to get the images to resize properly regardless when the load?
function resize($img) {
var max_size_w = 200;
var max_size_h = 200;
var h = $img.height();
var w = $img.width();
if (h > max_size_h) {
h = max_size_h;
w = Math.ceil($img.width() / $img.height() * max_size_h);
}
if (w > max_size_w) {
h = Math.ceil($img.height() / $img.width() * max_size_w);开发者_如何学C
w = max_size_w;
}
$img.css({ height: h, width: w });
}
$().ready(function() {
// Size the images correctly
$(".personPictureImage").each(function() {
$(this).find("img").load(function() { resize($(this)); });
});
});
UPDATE: The HTML
<div class="personPicture">
<div class="personPictureFrame">
<div class="personPictureImage">
<a href="../images/media/popup/46.png" class="lightbox">
<img src="../images/media/thumbnail/46.png" alt="">
</a>
</div>
<div class="personPictureFrameTL"></div>
<div class="personPictureFrameTR"></div>
<div class="personPictureFrameBL"></div>
<div class="personPictureFrameBR"></div>
</div>
</div>
Put a call to the function inside of a window load function to resize after all of the images have loaded:
$(window).load(function(){
// Size the images correctly
$(".personPictureImage").each(function() {
resize($(this));
});
});
Also using $().ready
has been deprecated, use $(function(){
or $(document).ready(function(){
$(document).ready(function(){
function resize($img) {
var max_size_w = 200;
var max_size_h = 200;
var h = $img.height();
var w = $img.width();
if (h > max_size_h) {
h = max_size_h;
w = Math.ceil($img.width() / $img.height() * max_size_h);
}
if (w > max_size_w) {
h = Math.ceil($img.height() / $img.width() * max_size_w);
w = max_size_w;
}
$img.css({ height: h, width: w });
}
$(".personPictureImage").each(function() {
$(this).find("img").load(function() { resize($(this)); });
});
}())
That should work.
精彩评论