我的帖子有一个 div,它可能包含不同大小的图像,我需要分别设置它们容器的宽度。我该怎么做?
<div class="panel">
<img id="screeny" src="http://localhost/531q3n.jpg"/>
</div>
这是我目前的尝试,但出了点问题:
var img = document.getElementById('screeny');
//or however you get a handle to the IMG
var width = img.clientWidth;
var height = img.clientHeight;
$('.panel').css("width",width+"px");
最佳答案
必须先加载图像,然后才能访问它的大小,如下所示:
var img = $('#screeny');
img.load(function() {
var width = img.width();
var height = img.height();
$('.panel').css("width", width);
});
编辑:对于不止一张图片,如果它们都在一个带有“面板”类的 div 中:
$("img", ".panel").each(function() {
$(this).load(function() {
var width = $(this).width();
var height = $(this).height();
$(this).parent().css("width", width);
});
});
关于javascript - 抓取图像高度并将其设置为其容器 jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8407239/