微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

根据图像比率添加CSS类

如何解决根据图像比率添加CSS类

| 我正在创建一个图像库,在一个页面上包含数十个横向和纵向图像。我想根据其方向使用动态添加的CSS类(即用于风景图像的\“。landscape \”)为每个图像设置样式。 我遇到了下面的代码(从2003年开始!),用于确定比率并为单个图像添加一个类,但是我需要为某个div ID中的所有图像自动添加这些类。老实说,我只是对JavaScript或jQuery不够了解,无法自行解决
<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> 
    

解决方法

使用jQuery:
$(\'#divID img\').each(function(){
    $(this).addClass(this.width > this.height ? \'landscape\' : \'portrait\');
});
    ,相当简单的jQuery:
$(\'#yourId\').find(\'img\').each(function(i,elem){
    var $this = $(this),ratio = $this.width() / $this.height();

    $this.addClass((ratio < 1) ? \'portrait\' : \'landscape\');
});
参见示例→     ,可以说,您所包含的div为
gallery
类,并且您正在使用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);
    });
});
这种方法更长,但是允许您添加更多规则(如果有任何理由,:) ..即:
if (width/height == 1) className = \"square\";
    ,如果设置img width / height干扰CSS,则可以将其设置为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>
编辑了mVChr的示例     

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。