【问题标题】:Jquery: Find image by width and add classJquery:按宽度查找图像并添加类
【发布时间】:2012-01-24 15:36:39
【问题描述】:

我有许多具有相同的 div,并且 div 内部包含一个图像:

<div class="card_div"> 
<img src="path" alt="name_image"> 
</div> 
<div class="card_div"> 
<img src="path" alt="name_image"> 
</div> 
<div class="card_div"> 
<img src="path" alt="name_image"> 
</div> 
<div class="card_div"> 
<img src="path" alt="name_image"> 
</div> 
.
.
.

我想找到一个 img,如果图像的宽度小于 200px,则只为这个宽度小于 200px 的 img 添加一个类。

例如:

var imgWidth = $(".card_div img").width();
if (imgWidth < 200) {
$(".card_div img").css({margin:"8px 8px 8px 17px", "background-color":"blue"});  
}

但这段代码为每个图像 div 添加了边距和背景我无法更改 div 名称。每个 div 都有相同的名称。

我只想将 css 属性添加到小于

有可能吗?谢谢

【问题讨论】:

  • 对不起,我有很多 div 具有相同的类...对不起错误:D 我已经编辑了帖子

标签: jquery css image width addclass


【解决方案1】:

您发布的 HTML 标记 不是最好的,但使用该确切标记我已经设置了这个示例来说明您将如何获得所需的结果:http://jsfiddle.net/xFSLN/1/

HTML:

<div class="card_div"><img src="http://placekitten.com/199/199" alt="name_image"></div> 
<div class="card_div"><img src="http://placekitten.com/200/200" alt="name_image"></div> 
<div class="card_div"><img src="http://placekitten.com/300/300" alt="name_image"></div> 
<div class="card_div"><img src="http://placekitten.com/100/100" alt="name_image"></div> 

CSS:

.under-200 {
    margin: 8px 8px 8px 17px;
    background-color: blue;
}

Javascript:

$('div.card_div]').find('img').each(function () {
     var $this = $(this), width = $this.width();
    if (width < 200) {
        $this.addClass('under-200');
    }
});

我会强烈建议您将 HTML 更改为更有效。

  1. 您的所有 ID 都应该是唯一的
  2. 请勿在您的 ID 中包含“#”
  3. 在适当的时候使用类名

更新:您更新了标记以进行改进。我已更新答案以反映您的更改。

【讨论】:

  • ID 不应以“#”开头。它应该是独一无二的。改为添加一个类。
  • @vinay McHerbie 像 OP 一样声明标记,我相信他知道这一点 - 请参阅他的建议列表的第 2 点。
  • @vinay,我的回答是使用提供的原始标记。
  • @hyperrjas,我已经更新了我的答案和 JSFiddle 示例以使用您更新的标记。
  • Wuauuuuuuuuuuu @McHerbie 工作正常:D 非常感谢!
【解决方案2】:

尝试以下方法:

$("div.card_div > img").filter(function() {
  return $(this).width() < 200;
).css({margin:"8px 8px 8px 17px", "background-color":"blue"});

或者,如果您有一个具有必要样式的 css 类:

$("div.card_div > img").filter(function() {
  return $(this).width() < 200;
).addClass('cssClassHere');

【讨论】:

    猜你喜欢
    • 2014-02-12
    • 1970-01-01
    • 1970-01-01
    • 2011-03-12
    • 2012-04-18
    • 2013-01-01
    • 2012-12-15
    • 1970-01-01
    • 2011-04-15
    相关资源
    最近更新 更多