javascript - 如何向包含特定尺寸图像的父 Div 添加类?

标签 javascript jquery

我想根据父 div 内图像的特定大小向父 div 添加一个类。

但是当我在父容器中添加更多 div 元素时,此 jquery 代码不起作用

代码看起来像这样

<div>
    <div>
        <div>
            <img src='http://4.bp.blogspot.com/-Go-gvkEm4Rw/UszzNls6EYI/AAAAAAAAEfQ/qds_K1jXgLE/s1600/doctype-hi-res1-960x305.jpg'/>
        </div>
    </div>
</div>

我想要一个jquery代码,它可以根据特定宽度的图像的大小向主父div添加类。

最佳答案

使用图像加载处理程序...就像

jQuery(function () {
    $('img').load(function () {
        //check the desired size here
        if (this.width > 48) {
            $(this).parents(':eq(2)').addClass('special')
        }
    }).filter(function () {
        return this.complete
    }).trigger('load')
})

演示:Fiddle

关于javascript - 如何向包含特定尺寸图像的父 Div 添加类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20993344/

相关文章:

javascript - 检索 json 数组中具有相同 id 的对象 (javascript)

javascript - 我需要一个以给定值开始的售票柜台

jquery - 检查href是否有class,如果有,则获取id

javascript - 使用 Bootstrap 的 Typeahead displayKey 函数返回值

javascript - 为什么这个 promise 不起作用?

javascript - Ajax,防止点击多个请求

javascript - 根据当前 URL React 渲染页脚

javascript - Node.js 内存使用量永远不会减少

javascript - 如何从 jquery 对话框中添加和删除表

javascript - 来自 JSON 的 Highcharts 堆积柱形图未绘制正确的值