Hey Guys. So this is more about me not knowing JS than being a real hard question.
I'm trying to write a little function in JS that I can call from jQuery to resize an i开发者_C百科mage. The thing is I have no idea how to return the values back to jQuery after the JS function runs. Here is what i have so far:
$('a').click(function() {
var slideshowHeight = $(this).closest('.stage').css('height')
var slideshowWidth = $(this).closest('.stage').css('width')
var newImageHeight = $(this).attr('data-height')
var newImageWidth = $(this).attr('data-width')
fit_within_box(slideshowWidth, slideshowHeight, newImageWidth, newImageHeight);
$(this).children('img').css('width',new_width);
$(this).children('img').css('width',new_height);
}
function fit_within_box(box_width, box_height, width, height)
{
var new_width = width
var new_height = height
var aspect_ratio = parseInt(width) / parseInt(height)
if (new_width > box_width)
{
new_width = box_width
new_height = int(new_width / aspect_ratio)
}
if (new_height > box_height)
{
new_height = box_height
new_width = int(new_height * aspect_ratio)
}
return (new_width, new_height)
}
As you can see, I'm trying to feed in some values and get back new_width and new_height.
Thanks for the help!
If you want to return both values at once, you could do it with an object literal...
return {
width: new_width,
height: new_height
};
you can try to return a JSON object like this:
return {
new_height:height,
new_width:width
};
and use it in your jquery function:
var fit_img = fit_within_box(...);
...
$(this).children('img').css('height',fit_img.new_height);
Hey, here's the working example, I've fixed some small mistakes e.g. you've used width twice on children('img');
jQuery:
$(function(){
$('a').click(function() {
var slideshowHeight=$(this).closest('.stage').height();
var slideshowWidth=$(this).closest('.stage').width();
var newImageHeight=$(this).attr('data-height');
var newImageWidth=$(this).attr('data-width');
var size=fit_within_box(slideshowWidth,slideshowHeight,newImageWidth,newImageHeight);
$(this).children('img').css({'width':size[0],'height':size[1]});
});
function fit_within_box(box_width,box_height,new_width,new_height){
var aspect_ratio=new_width/new_height;
if(new_width>box_width){
new_width=box_width;
new_height=Math.round(new_width/aspect_ratio);
}
if(new_height>box_height){
new_height=box_height;
new_width=Math.round(new_height*aspect_ratio);
}
return [new_width,new_height];
}
});
HTML with some wallpaper:
<div class="stage" style="width:200px;height:200px;">
<a href="#" data-width="1280" data-height="1024"><img src="wallpaper_1280x1024.jpg" /></a>
</div>
Cheers
G.
精彩评论