开发者

Adding CSS Class According to Image Ratio

I'm creating an image gallery with dozens of landscape and portrait images on a single page. I want to style each image with a dynamically added CSS class (i.e. ".landscape" for landscape images) according to its orientation.

I came across the code below (from 2003!) For determining the ratio and adding a class for a single image, but I need the classes to be added automatically for all images within a cert开发者_如何学运维ain div id. Honestly, I just don't know enough about JavaScript or jQuery to solve this on my own.

<script language="JavaScript" type="text/javascript">
<!--
function getDim() {
myImage = new Image;
myImage.src="myimage.gif";//path to image
document.divImage.src=myImage.src;
var imgProp;
var width = myImage.width;
var height = myImage.height;
var ratio = width/height;
if ( ratio > 1 ) {
document.getElementById('image').className="portrait";
}
else {
document.getElementById('image').className="landscape";
}
}
//-->
</script> 


with jQuery:

$('#divID img').each(function(){
    $(this).addClass(this.width > this.height ? 'landscape' : 'portrait');
});


Pretty straightforward jQuery:

$('#yourId').find('img').each(function(i,elem){
    var $this = $(this),
        ratio = $this.width() / $this.height();

    $this.addClass((ratio < 1) ? 'portrait' : 'landscape');
});

See example →


Lets say, that your containing div is of class gallery and you are using jQuery :)

$(document).ready(function(){
    $('.gallery img').each(function(){
        var width = $(this).width();
        var height = $(this).height();
        var className;
        if (width/height > 1) className = "portrait";
        else className = "landscape";
        $(this).addClass(className);
    });
});

This way is longer, but allows you to add more rules (if there is any reason to do so :).. ie.:

if (width/height == 1) className = "square";


If setting img width/height interferes with your css, you can set it as data-width/data-height:

  $('#your-div-Id').find('img').each(function(i,elem){
      var $this = $(this),
          ratio = $this.attr('data-width') / $this.attr('data-height');
      $this.addClass((ratio < 1) ? 'portrait' : 'landscape');
  });

HTML:

<div id="your-div-Id">
    <img src="#" data-width="60" data-height="30" />
</div>

Edited mVChr's example

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜