.height()
.height() 返回: Integer
描述: 為匹配的元素集合中獲取第一個元素的當(dāng)前計(jì)算高度值。
version added: 1.0.height()
.css('height')
和 .height()
之間的區(qū)別是后者返回一個沒有單位的數(shù)值(例如,400
),前者是返回帶有完整單位的字符串(例如,400px
)。當(dāng)一個元素的高度需要數(shù)學(xué)計(jì)算的時候推薦使用.height()
方法 。
這個方法同樣能計(jì)算出window和document的高度。
$(window).height(); // returns height of browser viewport $(document).height(); // returns height of HTML document
注意.height()
總是返回內(nèi)容寬度,不管CSS box-sizing
屬性值。
舉例:
顯示各個高度。注意這個來自值iframe的值可能小于你的預(yù)期。黃色高亮顯示iframe body。
<!DOCTYPE html>
<html>
<head>
<style>
body { background:yellow; }
button { font-size:12px; margin:2px; }
p { width:150px; border:1px red solid; }
div { color:red; font-weight:bold; }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<button id="getp">Get Paragraph Height</button>
<button id="getd">Get Document Height</button>
<button id="getw">Get Window Height</button>
<div> </div>
<p>
Sample paragraph to test height
</p>
<script>
function showHeight(ele, h) {
$("div").text("The height for the " + ele +
" is " + h + "px.");
}
$("#getp").click(function () {
showHeight("paragraph", $("p").height());
});
$("#getd").click(function () {
showHeight("document", $(document).height());
});
$("#getw").click(function () {
showHeight("window", $(window).height());
});
</script>
</body>
</html>
Demo:
.height( value ) 返回: jQuery
描述: 給每個匹配的元素設(shè)置CSS高度。
-
version added: 1.0.height( value )
value一個正整數(shù)代表的像素?cái)?shù),或是整數(shù)和一個可選的附加單位(默認(rèn)是:“px”)(作為一個字符串)。
-
version added: 1.4.1.height( function(index, height) )
function(index, height)返回用于設(shè)置高度的一個函數(shù)。接收元素的索引位置和元素舊的高度值作為參數(shù)。
當(dāng)調(diào)用.height(value)
方法的時候,這個“value”參數(shù)可以是一個字符串(數(shù)字加單位)或者是一個數(shù)字。如果這個“value”參數(shù)只提供一個數(shù)字,jQuery會自動加上單位px。如果只提供一個字符串,任何有效的CSS尺寸都可以為高度賦值(就像100px
, 50%
, 或者 auto
)。注意在現(xiàn)代瀏覽器中,CSS高度屬性不包含padding, border, 或者 margin。
如果沒有給定明確的單位(像'em' 或者 '%'),那么默認(rèn)情況下"px"會被直接添加上去(也理解為"px"是默認(rèn)單位)。
注意.height('value')
設(shè)置的容器寬度是根據(jù)CSS box-sizing
屬性來定的, 將這個屬性值改成border-box
將造成這個函數(shù)改變成獲取這個容器的outerHeight替換原來的內(nèi)容高度。
舉例:
點(diǎn)擊每個div時設(shè)置該div高度為30px,并改變顏色。
<!DOCTYPE html>
<html>
<head>
<style>div { width:50px; height:70px; float:left; margin:5px;
background:rgb(255,140,0); cursor:pointer; } </style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<script>$("div").one('click', function () {
$(this).height(30)
.css({cursor:"auto", backgroundColor:"green"});
});</script>
</body>
</html>