简体   繁体   English

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

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

Hi let me start with the codes. 嗨,让我从代码开始。

<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>

Ok, so basically what I want is that the divs with an image that is 785 should get a class named large added to it, and the divs with an image that is 390 should get a class named small. 好的,基本上,我想要的是图像为785的div应该添加一个名为large的类,图像为390的div应该获得一个名为small的类。

So it should look like this. 所以它应该看起来像这样。

<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>

and so on. 等等。 This is what I've tried to so far. 到目前为止,这是我尝试过的。

$(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");
    }
  }
});

I chose to use .attr instead of .width because the images probably won't be finished loading when the script runs. 我选择使用.attr而不是.width,因为脚本运行时图像可能不会完成加载。

Any help would be appriciated! 任何帮助都将被申请!

Based on your code snippet I couldn't tell if you wanted to set images with width 786 as larget so heres a way to do it for ranges: 根据您的代码片段,我无法确定您是否要将宽度786设置为较大的图像,因此这里提供了一种针对范围的方法:

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

You can just use one selector: 您可以只使用一个选择器:

$("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