javascript - jquery获取每张图片的宽度

标签 javascript jquery html css

我试图在我的类 img-wrap 中获取每个图像的宽度,并将该宽度应用于每个元素的 img-caption 类。 我下面的代码仅适用于第一项。

    <div class="img-wrap">
        <img src="http://lorempixel.com/300/100" />
        <div class="img-caption">aa</div>
    </div>
    <div class="img-wrap">
        <img src="http://lorempixel.com/400/100" />
        <div class="img-caption"></div>
    </div>
    <div class="img-wrap">
        <img src="http://lorempixel.com/500/100" />
        <div class="img-caption">cc</div>
    </div>

    <script>
    var imgwidth = 0;
    $('.img-wrap').each(function (index, value) {
        imgwidth = $('.img-wrap img').width();
        if ($('.img-caption').text() === '') {} else {
            $(this).css("background-color", "#000");
            $(this).css("color", "#fff");
            $(this).css("width", imgwidth);
        }
    });
    </script>

然后该宽度将应用于所有类。我在这里缺少什么来获得应用于每个 img-caption 的宽度。 例如,在我的示例中,不是它们都是 300 像素宽,因为这是第一张图像的宽度,它们应该是 300,400,500。我有 else 之类的,因为我可能稍后会在 if 中添加一些与问题无关的内容。

最佳答案

尝试:

imgwidth = $(this).children('img').width();

这是工作示例:http://jsfiddle.net/EmE39/

关于javascript - jquery获取每张图片的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20038158/

相关文章:

javascript - JS 对象属性被意外重写

javascript - 获取类型错误 : invalid 'in' operand obj while fetching data using ajax

javascript - JQuery 脚本加载时间

javascript - 我如何避免使用 JQuery 更改所有 id?

javascript - 检查隐藏表单输入在表单提交上是否具有值

Javascript 在类中选择下拉选项

javascript - 如何识别来自 JS 脚本的 http 请求和 HTML<FORM>submit 事件之间的区别

javascript - 如何让我的脚本在 WordPress 中运行

html - 如何从 css {} 部分访问类?

html - CSS 位置 : absolute - understanding how to center text inside a div box