Rails 3 / Javascript- Set width of div
I hate to ask the same question that's on here several times but I'm struggling to开发者_如何学C bring it all together.
I'm doing something I think should be pretty simple with javascript. Each time a page loads, I need to find with width of an img. With that img width, I need to assign it to the width of the div. So far I've come up with:
$(window).load(function() {
var imgWidth = $("img").width();
$function setWidth(imgWidth){
$("#main").css("width":imgWidth);
return false;
});
});
For each page that loads, I want to assign with width of the img (only one on a page) to my imgWidth variable. I then pass that variable into a function to change the css of my div with an id of mmain to with imgWidth.
Basically, I'm stuck. I can't get anything to work and am having problems seeing why I can't get it to resize.
Anyway, appreciate the help. I'm on rails 3, using jquery.
Using jQuery it's
$(document).ready(function() {
$("#main").width($("img").first().width());
});
Here were your mistakes:
You should call document ready
$("img")
retrieves an array of elements. So either take the first like I did or provide a precise matcher.You're badly defining a function you don't call
You're badly passing value to css attribute: Doc here.
I think you just need to change
$("#main").css("width":imgWidth);
to
$("#main").css("width",imgWidth);
docs
Have you considered just floating the div? E.g.
div#picture {
float: left;
}
This way the width of the div will adapt to the size of the image - no JS required.
HTH
精彩评论