javascript - 抓取图像高度并将其设置为其容器 jquery

标签 javascript jquery html css

我的帖子有一个 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/

相关文章:

javascript - 如何在 Android 3.1 上以编程方式滚动 HTML DIV?

javascript - 从 slider Fabricjs 更改事件对象的不透明度

javascript - 将 D3 包含在 ERB 循环中

javascript - Jquery中如何使用fancybox

javascript - 多个弹出窗口但只有一个有效...为什么?

javascript - 字符串替换为 'any character' 掩码问题

javascript - 在d3.js中使用.filter()返回多个图表上对应x轴点的数据

javascript - 尝试上传文件时无法读取未定义的属性 'length'

javascript - 单击 anchor 标记后如何运行 jquery?

javascript - "async"的使用已被弃用。在 ajax/Jquery 中进行同步调用的替代方法