3

Ok so I've been at this for hours to no avail. What I want to do, is write a script that does the following: when an image is larger than it's container, it adds the class "large" to it. But, if an image is smaller than it's container, it adds the class small to it. Here's what I have so far:

$(window).load(function() {
var screenImage = $('.image img');

// Create new offscreen image to test
var theImage = new Image();
theImage.src = screenImage.attr('src');

// Get accurate measurements from that.
var imageWidth = theImage.width;

// Find post width
var postWidth = $('.image').innerWidth();

$('.image img').each(function() {
    if (imageWidth > postWidth) {
        $('.image').find('img').addClass('large');
    } else {
        $('.image').find('img').addClass('small');
    }
});
});

Here's an example: http://jsfiddle.net/TheInfection/6fUgr/8

Instead, the end result for this script is that all images get the "large" class added to them. I've spent hours on Google, the jQuery website, etc. and I couldn't find the solution anywhere. Could someone help me?

4

3 回答 3

4

看看这是否是您正在寻找的。

演示

var postWidth = $('.post').innerWidth();
$('.image img').removeClass('large, small') ;
    $('.image img').each(function() {

        var imageWidth = this.width;
        if (imageWidth > postWidth) {
            $(this).addClass('large');
        } else {
            $(this).addClass('small');
        }
    });
于 2013-05-04T02:42:11.283 回答
3

据我了解,您的逻辑有几个错误:

  1. $('.image img')这会选择超过 1 个图像对象,因此该src属性不会是预期的那个。
  2. 您应该重新计算每个图像的大小并将一个类分配给一个图像对象。为每个图像$('.image').find('img').addClass('large');分配.large类。

示例显示了方法的正确用法,.each(function(idx, item)用于您的目的。

于 2013-05-04T02:45:15.057 回答
1

看起来你想要做的是限制元素内任何图像的宽度.post

您可以使用 CSS 属性来实现这一点max-width,该属性在 CSS2 中可用:

http://www.w3schools.com/cssref/pr_dim_max-width.asp

浏览器支持

除非您需要支持 ie6 及更低版本,否则这应该没问题 - 即使您这样做,也有可用的 polyfill:

http://caniuse.com/minmaxwh


看到它在行动

http://jsfiddle.net/vonky/NYF2v/

标记 - HTML

<div class="post">
        <img src="http://placehold.it/200x200">
            <br /><br />
        <img src="http://placehold.it/600x600">
</div>

标记 - CSS

.post {
    width: 300px; /* cap the width of our DIV.post */
    margin: 0 auto; /* for visual reference, let's center our element */
    background-color: #00B2EE; /* for visual reference, let's make it blue */
    text-align: center; /* for visual reference, let's center our content */
}

.post img {
    max-width: 100%; /* this is the magical faerie dust */
}

如果您出于其他原因添加类并且需要添加类,PSL 的初始脚本看起来应该可以工作。

于 2013-05-04T02:47:11.223 回答