我拼凑了这个 jQuery 函数。其目的是计算内部所有 img 元素的边距,div.article
以平衡图像的高度与文档的基线网格,即 20 px。为了匹配我的基线网格,每个图像高度应该是 20 的倍数。如果不是这种情况,例如一个图像的高度是 154 px,该函数会为 img 添加 6 px 边距,以便与基线平衡网格恢复。
该功能正常工作,所以我的实际问题是:由于我不是程序员,我想知道我的代码是否非常糟糕,虽然它正在工作,如果是这样,如何改进代码?
jQuery代码:
$('div.article img').each(function() {
// define line height of CSS baseline grid:
var line_height = 20;
// capture the height of the img:
var img_height = $(this).attr('height');
// divide img height by line height and round up to get the next integer:
var img_multiply = Math.ceil(img_height / line_height);
// calculate the img margin needed to balance the height with the baseline grid:
var img_margin = (img_multiply * line_height) - img_height;
// if calculated margin < 5 px:
if (img_margin < 5) {
// then add another 20 px to avoid too small whitespace:
img_margin = img_margin + 20;
}
// if img has caption:
if ($($(this)).next().length) {
// then apply margin to caption instead of img:
$($(this)).next().attr('style', "margin-bottom: " + img_margin + "px;");
} else {
// apply margin to img:
$(this).attr('style', "margin-bottom: " + img_margin + "px;");
}
});
HTML 代码示例,带标题的 img:
<div class="article">
<!-- [...] -->
<p class="image">
<img src="http://example.com/images/123.jpg" width="230" height="154" alt="Image alt text goes here" />
<small>Image Caption Goes Here</small>
</p>
<!-- [...] -->
</div>
HTML 代码示例,不带标题的 img:
<div class="article">
<!-- [...] -->
<p class="image">
<img src="http://example.com/images/123.jpg" width="230" height="154" alt="Image alt text goes here" />
</p>
<!-- [...] -->
</div>
编辑:根据 Russ Cam 的建议改进代码:
var line_height = 20;
var min_margin = 5;
$('div.article img').each(function() {
var $this = $(this); // prefixed variable name with $ to remind it's a jQuery object
var img_height = $this.height();
var img_margin = ((Math.ceil(img_height / line_height)) * line_height) - img_height;
img_margin = (img_margin < min_margin)? img_margin + line_height : img_margin;
if ($this.next().length) {
$this.next().css({'margin-bottom' : img_margin + 'px'});
} else {
$this.css({'margin-bottom' : img_margin + 'px'});
}
});