【问题标题】:jQuery - Filter Images based on actual sizejQuery - 根据实际大小过滤图像
【发布时间】:2012-10-05 22:13:26
【问题描述】:

图像源拥有真实的图像尺寸(宽度/高度)。在有 5 张图片的div#pics 中,3 张图片是 16X16,2 张图片是 2x2。两个 2x2 图像都应用了一个类,使它们成为 16x16,其他 3 个图像是 16x16。问题是,当我以这种方式过滤时:

var Images = $('#pics img');
var FilteredImages = Images.filter(function(){
    return ($(this).width() == 16) || ($(this).height() == 16)
});

FilteredImages 包含所有 5 个图像,因为它考虑了使 2 个 2x2 图像为 16x16 的类。 FilteredImages 怎么能只保存源图像大小(不是 css)为 16x16 的 3 张图像?

【问题讨论】:

    标签: jquery image filter dimensions image-size


    【解决方案1】:

    您可以将图像添加到临时对象以获取其原始大小:

    function getImgSize(imgSrc) {
      var newImg = new Image();
    
      newImg.onload = function() {
        var height = newImg.height;
        var width = newImg.width;
        alert ('The image size is '+width+'*'+height);
      }
    
      newImg.src = imgSrc; // this must be done AFTER setting onload
    
    }
    

    在此处查看答案: Determine original size of image cross browser?

    【讨论】:

    • FilteredImages 怎么能只保存源图像大小(不是 css)为 16x16 的 3 张图像?
    【解决方案2】:
    $('#pics img[width=16][height=16]').css({border:'1px solid red'});
    

    【讨论】:

    • 这完全依赖于设置的height/width 属性。情况并非总是如此。
    • 没错,但问题不够具体,所以我认为是这样,出于 SEO 和渲染目的,我总是为图像设置这些属性。
    • 这很公平,我的评论不是为了批评,只是一个警告。 =)
    【解决方案3】:

    我建议:

    var Images = $('#pics img'),
        FilteredImages = Images.filter(function(){
            var that = this;
            return (that.naturalWidth == '16px') || (that.naturalHeight == '16px')
        });
    

    参考资料:

    【讨论】:

    • 只是出于好奇,为什么在您的示例中使用 var that = this?
    • 因为我喜欢缓存我多次使用的变量; this(我认为)不涉及导航 DOM,但这是我在访问相对于当前 this 节点/对象的其他节点时养成的习惯。
    • 大卫,感谢您的快速回复。只是想知道,这个解决方案是跨浏览器的吗?
    • 我完全同意缓存变量,我也经常这样做,但我从未缓存过“this”,因为我认为它已经被缓存了。我将对此进行更多研究,以便我可以正确地在脑海中获得正确的想法。谢谢
    • @Wonka,说实话,我有点怀疑;但恐怕我没有方便的 IE 进行测试。
    猜你喜欢
    • 1970-01-01
    • 2012-09-15
    • 2011-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多