jQuery 中 innerHeight 和 outerHeight 有何不同?


jQuery 的 innerHeight

innerHeight() 方法獲取第一個匹配元素的內部高度(不包括邊框,包括內邊距)。

例子

可嘗試執行以下程式碼,瞭解如何在 jQuery 中使用 innerHeight

即時演示

<html>

   <head>
      <title>jQuery innerHeight() method</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
           
            $("div").click(function () {
               var color = $(this).css("background-color");
               var height = $(this).innerHeight();
               $("#result").html("Inner Height is <span>" +
                  height + "</span>.");
               $("#result").css({'color': color, 'background-color':'gray'});
               $("#result").height( height );
            });
               
         });
      </script>
       
      <style>
         #div1{
             margin:10px;
             padding:12px;
             border:2px solid #666;
             width:60px;
         }
             
         #div2 {
            margin:15px;
            padding:5px;
            border:5px solid #666;
            width:60px;
         }
         
         #div3 {
            margin:20px;
            padding:4px;
            border:4px solid #666;
            width:60px;
           
         }
         #div4 {
             margin:5px;
             padding:3px;
             border:3px solid #666;
             width:60px;
         }
      </style>
   </head>
   
   <body>
   
      <p>Click on any square:</p>
      <span id = "result"> </span>
       
      <div id = "div1" style = "background-color:blue;"></div>
      <div id = "div2" style = "background-color:pink;"></div>
      <div id = "div3" style = "background-color:#123456;"></div>
      <div id = "div4" style = "background-color:#f11;"></div>
       
   </body>  
</html>

jQuery 的 outerHeight()

outerHeight() 返回第一個匹配元素的外高度。包括內邊距和邊框。

例子

可嘗試執行以下程式碼,獲取 jQuery 中的外高度

即時演示

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        alert("Outer Height of div element: " + $("div").outerHeight());
    });
});
</script>
</head>
<body>

<div style="height:200px;width:500px;padding:10px;margin:10px;border:1px solid red; background-color:blue;"></div><br>
<button>Get Outer Height of div</button>

</body>
</html>

更新時間:2019-12-10

348 次瀏覽

啟動你的 事業

完成學習課程,獲得認證

入門
廣告