jQuery outerHeight()

admin發表於2017-02-15
此方法獲得匹配集合中第一個元素的當前計算的外部高度(包括padding,border和可選的marginr),或設定每一個匹配元素的外部高度。

語法結構一:

[JavaScript] 純文字檢視 複製程式碼
.outerHeight([includeMargin ])

引數解析:

includeMargin:可選,一個布林值,表明是否在計算時包含元素的margin值。

返回元素的高度,包含上下padding值,border值和可選擇性的margin,單位是畫素。如果在一組空的元素集合上呼叫,返回undefined(在jQuery3.0之前返回null)。

jQuery1.2.6版本新增。

語法結構二:

[JavaScript] 純文字檢視 複製程式碼
.outerHeight(value)

引數解析:

value:可以是一個整數(可以是字串形式),單位預設是px),或者一個帶單位的整數(字串)。

設定所有匹配元素的外部高度。

jQuery1.8版本新增。

語法結構三:

[JavaScript] 純文字檢視 複製程式碼
.outerHeight(function(index,oldHeight))

引數解析:

function:返回匹配元素新外部高度的回撥函式。index:可選,當前元素在匹配元素集合中的索引(從0開始),oldHeight:可選,當前匹配元素的外部高度值。在函式中,this指向當前元素。

也就是outerHeight函式的引數是function函式的返回值。

設定所有匹配元素的外部高度。

jQuery1.8版本新增。

程式碼例項:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
p{
  background-color:green;
  height:100px;
  width:200px;
  padding:10px;
  margin:15px;
  border:5px solid red;
}
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript"> 
$(document).ready(function(){ 
  $("#bt").click(function () {
    $("p").text($("p").outerHeight(true))
  }); 
}); 
</script>
</head>
<body>
<p>螞蟻部落</p>
<input type="button" id="bt" value="檢視演示"/>
</body>
</html>

獲取匹配元素的外部高度值,引數為true,表示把margin計算在內。

[HTML] 純文字檢視 複製程式碼執行程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
p{
  background-color:green;
  height:100px;
  width:200px;
  margin:15px;
  padding:10px;
  border:5px solid red;
}
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript"> 
$(document).ready(function(){ 
  $("#bt").click(function () {
    $("p").outerHeight(180)
  }); 
}); 
</script>
</head>
<body>
<p>螞蟻部落</p>
<input type="button" id="bt" value="檢視演示"/>
</body>
</html>

此時外部高度不包括margin;元素的padding和border值不會改變,所以元素height會被重置為150px。

[HTML] 純文字檢視 複製程式碼執行程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
p{
  background-color:green;
  height:100px;
  width:200px;
  padding:10px;
  margin:15px;
  border:5px solid red;
}
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript"> 
$(document).ready(function(){ 
  $("#bt").click(function () {
    $("p").outerHeight(function (index, h) {
      return h + 50;
    })
  }); 
}); 
</script>
</head>
<body>
<p>螞蟻部落</p>
<input type="button" id="bt" value="檢視演示"/>
</body>
</html>

h是元素原本內部高度,上面的程式碼也就是給元素外部高度再增加50px。

相關文章