问题
I want a div to get an inline style of the image it wraps around.
Pen here: http://codepen.io/stevenmorgan94/pen/xuEwm
HTML
<div class="box">
<img src="http://placehold.it/250x150" />
</div>
JS
var img = $(".box > img");
$(".box").css({width:img.width(), height:img.height()});
So jquery get image dimensions, add inline style to .box with the width and height
回答1:
jonathan didn't get it right. His solution not about what was asked. Correct one is
var img = $(".box > img");
$(".box").css({width:img.width(), height:img.height()});
回答2:
Add this to your JavaScript requires jQuery
$(".box > img").css({width:250,height:250});
Using native JavaScript, but you need to give the image an ID
var myImg = document.getElementById('myImgID');
myImg.style.height = '250px';
myImg.style.width = '250px';
UPDATED AFTER QUESTION CHANGED ABOVE:
@Gugic got the right answer above after question was edited :)
来源:https://stackoverflow.com/questions/19729033/jquery-get-image-dimensions-apply-to-div