jQuery height()和innerHeight()用法代码实例

2021年4月1日18:22:34 发表评论 722 次浏览

height()是jQuery中的一个内置方法,用于检查元素的高度,但它不会检查元素的padding、border和margin。

语法如下:

$("param").height()

参数:此函数不接受任何参数。

返回值:它返回选定元素的高度。

jQuery代码显示height()函数的工作

代码1:

<html>
  
<head>
     <script src="https://ajax.googleapis.com/ajax/libs/
                  jquery/3.3.1/jquery.min.js"></script>
     <script>
         $(document).ready(function() {
             $("button").click(function() {
                 var msg = "";
                 msg += "height of div: " + $("#demo").height();
                 $("#demo").html(msg);
             });
         });
     </script>
     <style>
         #demo {
             height: 150px;
             width: 350px;
             padding: 10px;
             margin: 3px;
             border: 1px solid blue;
             background-color: lightgreen;
         }
     </style>
</head>
  
<body>
     <div id = "demo"></div>
     <button>Click Me!!!</button>
     <p>Click on the button and check the height of the
        element(excluding padding).</p>
</body>
  
</html>

输出如下:

在点击"点击我"按钮之前,

jQuery |带有示例的height()和innerHeight()1

点击"点击我"按钮后,

jQuery |带有示例的height()和innerHeight()2

jQuery还包括innerHeight()方法,它用于检查元素的内部高度,包括填充。

语法如下:

$("param").innerHeight()

参数:此函数不接受任何参数。

返回值:它返回选定元素的内部高度。

代码2:

<html>
  
<head>
     <script src="https://ajax.googleapis.com/ajax/libs/
                  jquery/3.3.1/jquery.min.js"></script>
     <script>
         $(document).ready(function() {
             $("button").click(function() {
                 var msg = "";
                 msg += "Inner Height of div: " + $("#demo").
                         innerHeight() + "</br>";
                 $("#demo").html(msg);
             });
         });
     </script>
</head>
<style>
     #demo {
         height: 150px;
         width: 350px;
         padding: 10px;
         margin: 3px;
         border: 1px solid blue;
         background-color: lightgreen;
     }
</style>
  
<body>
     <div id = "demo"></div>
     <button>Click Me!!!</button>
     <p>Click on the button and check the innerHeight of
        an element(includes padding).</p>
</body>
  
</html>

输出如下:

在点击"点击我"按钮之前,

jQuery |带有示例的height()和innerHeight()3

点击"点击我"按钮后,

jQuery |带有示例的height()和innerHeight()4

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: