.height()

Contents:

.height() 官网原E文: Integer

描述: 为匹配的元素集合中获取第一个元素的当前计算高度值。

  • version added: 1.0.height()

.css('height').height()之间的区别是后者返回一个没有单位的数值(例如,400),前者是返回带有完整单位的字符串(例如,400px)。当一个元素的高度需要数学计算的时候推荐使用.height() 方法 。

这个方法同样能计算出window和document的高度。

$(window).height();   // returns height of browser viewport
$(document).height(); // returns height of HTML document

注意.height()总是返回内容宽度,不管CSS box-sizing属性值。

举例:

显示各个高度。注意这个来自值iframe的值可能小于你的预期。黄色高亮显示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>&nbsp;</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 ) 官网原E文: jQuery

描述: 给每个匹配的元素设置CSS高度。

  • version added: 1.0.height( value )

    value一个正整数代表的像素数,或是整数和一个可选的附加单位(默认是:“px”)(作为一个字符串)。

  • version added: 1.4.1.height( function(index, height) )

    function(index, height)返回用于设置高度的一个函数。接收元素的索引位置和元素旧的高度值作为参数。

当调用.height(value)方法的时候,这个“value”参数可以是一个字符串(数字加单位)或者是一个数字。如果这个“value”参数只提供一个数字,jQuery会自动加上单位px。如果只提供一个字符串,任何有效的CSS尺寸都可以为高度赋值(就像100px, 50%, 或者 auto)。注意在现代浏览器中,CSS高度属性不包含padding, border, 或者 margin。

如果没有给定明确的单位(像'em' 或者 '%'),那么默认情况下"px"会被直接添加上去(也理解为"px"是默认单位)。

注意.height('value')设置的容器宽度是根据CSS box-sizing属性来定的, 将这个属性值改成border-box将造成这个函数改变成获取这个容器的outerHeight替换原来的内容高度。

举例:

点击每个div时设置该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>

Demo:

jQuery 1.6 API 中文版Clove整理、修订