区分垂直和水平图像格式jQuery

时间:2017-02-03 19:24:07

标签: javascript jquery html css

我想区分图像是垂直还是水平格式并添加特殊类。我用它来完全用我的形象填充我的div。

我的HTML:

<a href="images/gallerie/image-1.jpg" data-lightbox="image-1" class="impression">
    <img src="images/gallerie/image-1.jpg">
</a>

我的CSS:

.wide {
    height: 100%;
    width: auto;
}

.tall {
    height: auto;
    width: 100%;
}

我的JS(jQuery):

$('.impression').find('img').each(function() {
    if($(this).width() / $(this).height() > 1) {
        $(this).addClass('wide');
    }

    else {
        $(this).addClass('tall');
    }
});

它有时只能起作用,我不知道为什么。 在我的iPhone上它永远不会(Chrome)。

是否还有其他解决方案,或者有时可能有效的原因?

谢谢!

2 个答案:

答案 0 :(得分:2)

您需要使用加载事件处理程序,以便在检查维度

之前加载图像
$('.impression').find('img').on('load',(function() {
    // image is loaded now
    if($(this).width() / $(this).height() > 1) {
        $(this).addClass('wide');
    }

    else {
        $(this).addClass('tall');
    }
});

由于jQuery将在内部使用eacheach将成为图像实例

,因此不需要this

答案 1 :(得分:1)

最有可能的是,您过早运行该功能并且尚未加载图像。为了确保您可以始终console.log() .width().height()的值。

检查图片尺寸时确保图片已加载的最佳方法是使用load事件。

$('img').on('load', function(){
  // do your thing...
})

其余的都是错的,正如@charlietfl所指出的那样。 load的{​​{1}}事件不会传播。

更好的是,不要将侦听器绑定到每个img,只需在img上为所有图像绑定一个,包括稍后将加载的图像,使用一些奇特的异步方法:

body

每当$('body').on('load', 'img', function(){ // do your thing... }) <img>在您的DOM中load时,第二个版本就会运行,而不仅仅是在您运行script时。 < / p>