繁体   English   中英

将类添加到包含一定宽度图像的div中

[英]Add class to divs which contains an image of a certain width

嗨,让我从代码开始。

<div class="nyhet"> <img src="#" width="785" class="attachement-full" /></div>
<div class="nyhet"> <img src="#" width="390" class="attachement-full" /></div>
<div class="nyhet"> <img src="#" width="785" class="attachement-full" /></div>
<div class="nyhet"> <img src="#" width="390" class="attachement-full" /></div>
<div class="nyhet"> <img src="#" width="785" class="attachement-full" /></div>
<div class="nyhet"> <img src="#" width="390" class="attachement-full" /></div>
<div class="nyhet"> <img src="#" width="785" class="attachement-full" /></div>
<div class="nyhet"> <img src="#" width="390" class="attachement-full" /></div>

好的,基本上,我想要的是图像为785的div应该添加一个名为large的类,图像为390的div应该获得一个名为small的类。

所以它应该看起来像这样。

<div class="nyhet large"> <img src="#" width="785" class="attachement-full" /></div>
<div class="nyhet small"> <img src="#" width="390" class="attachement-full" /></div>
<div class="nyhet large"> <img src="#" width="785" class="attachement-full" /></div>

等等。 到目前为止,这是我尝试过的。

$(document).ready(function(){
  var x = $(".nyhet").length;
  for (var i=0; i<x;i++){
    n = $(".attachement-full:eq(i)").attr("width");
    if (n<785) {
      $(".nyhet:eq(i)").addClass("small");
    } else {
      $(".nyhet:eq(i)").addClass("large");
    }
  }
});

我选择使用.attr而不是.width,因为脚本运行时图像可能不会完成加载。

任何帮助都将被申请!

根据您的代码片段,我无法确定您是否要将宽度786设置为较大的图像,因此这里提供了一种针对范围的方法:

$(".nyhet img").each(function() {
    var $par = $(this).parent(".nyhet");
    if(this.offsetWidth >= 785) {
        $par.addClass("large");
    } else {
        $par.addClass("small");
    }
})

您可以只使用一个选择器:

$("img[width=785]").parent(".nyhet").addClass("large");
$("img[width=390]").parent(".nyhet").addClass("small");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM