0

正如标题所暗示的,我希望有一点 jQuery - 如果图像小于定义的宽度,它会为某个元素添加一个类。对我来说,这似乎很容易,但由于某种原因它不起作用。

$(document).ready(function() {
    var image = $('.work-each img');
        if (image.width() < 500) {
            $('.work-text').addClass('work-text-small');
        }
});

如果在每个 .work-each 下找到的图像小于 500 像素,则应该向元素 'work-text' 添加一个类 'work-text-small'。

HTML 示例(每个)

<div class="work-each">
   <div>
      <img src=""/>
      <div class="work-text">
         <p>Title</p>
         <p>Text</p>
      </div>
   </div>
</div>
<div class="work-each">
   <div>
      <img src=""/>
      <div class="work-text">
         <p>Title</p>
         <p>Text</p>
      </div>
   </div>
</div>
<div class="work-each">
   <div>
      <img src=""/>
      <div class="work-text">
         <p>Title</p>
         <p>Text</p>
      </div>
   </div>
</div>

谢谢,R

4

2 回答 2

7

Use load instead, when DOM is ready only img tag is defined but the image isn't loaded yet. Its size comes when it's fully loaded

$(window).load(function () {
    var image = $('.work-each img');
    if (image.width() < 500) {
        $('.work-text').addClass('work-text-small');
    }
});

However as @rdck pointed if there are more images with class=".work-each img" code won't work so in that case you go trough each image and apply the class

$(window).load(function () {
    var image = $('.work-each img');
    image.each(function () {
        var that = $(this);
        if (that.width() < 500) {
            that.next('div.work-text').addClass('work-text-small');
        }
    })

});
于 2013-01-13T16:13:36.910 回答
1

如果您使用服务器代码获取尺寸并相应地设置类,则无需等待图像加载,并且 css 会在 html 存在时立即生效

于 2013-01-13T16:37:18.007 回答