jQuery實現的多列元素高度相等

antzone發表於2017-04-02

在實際應用中,可能為了實現整齊劃一,會將多列的高度設定為相等。

下面就通過程式碼例項介紹一下如何利用jQuery實現此功能。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
.antzone{
  width:100px;
  height:300px;
  background:blue;
  float:left;
  margin:10px;
}
</style>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
  var maxHeight = -1;
  $('.antzone').each(function() {
    maxHeight = maxHeight > $(this).height() ? maxHeight : $(this).height();
  });
  $('.antzone').each(function() {
    $(this).height(maxHeight);
  });
});
</script>
</head>
<body>
<div class="antzone"></div>
<div class="antzone" style="height:200px;"></div>
<div class="antzone" style="height:100px;"></div>
</body>
</html>

上面的程式碼實現了我們的要求,下面介紹一下它的實現過程。

一.程式碼註釋:

(1).$(document).ready(function(){}),當文件結構完全載入完畢再去執行函式中的程式碼。

(2).var maxHeight = -1,宣告一個變數並賦初值為-1,它是用來儲存最終的最大高度。

(3).$('.antzone').each(function() {

  maxHeight = maxHeight > $(this).height() ? maxHeight : $(this).height();

}),遍歷每一個class屬性值為antzone的元素。

然後使用三元運算子獲取最大的高度。

(4).$('.antzone').each(function() {

  $(this).height(maxHeight);

}),將所有的元素高度設定為這個最大高度。

二.相關閱讀:

(1).each()方法可以參閱jQuery each()一章節。

(2).三元運算子可以參閱三元運算子用法詳解一章節。

(3).height()方法可以參閱jQuery height()一章節。

相關文章