jQuery Get Image Dimensions, Apply To Div

 ̄綄美尐妖づ 提交于 2019-12-24 19:26:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!