0

I would like to set the width of a div based on the width of an image that has been scaled to fit the viewing screen.

Now, I'm not a platinum grade programmer, but from what I gather this may be done using JavaScript to measure the width of the image and then outputting that result to the CSS. However I have no clue how to do this and can't find any decent tutorials. If anyone could point me to a tutorial or another good method for achieving my end that would be lovely.

Many thanks.

4

2 回答 2

2

This is very easily done with jQuery...

$('div').css( 'width', $('img').width() + 'px' );

See .width()

Here is a demo.

于 2012-08-04T07:15:52.767 回答
2

In JS (no jQuery) you can use style.width and offsetWidth. For example:

var w = document.getElementById('img_id').offsetWidth;
document.getElementById('div_id').style.width = w + 'px';​​​​​​​​​​​​​​​​​​

Where 'img_id' is the id of the img, and 'div_id' is the id of the div.

JSFiddle here.

于 2012-08-04T07:26:02.443 回答