问题描述
|
我正在创建一个图像库,在一个页面上包含数十个横向和纵向图像。我想根据其方向使用动态添加的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的示例