×

JS获取隐藏元素的高度

作者:andy0012019.10.12来源:Web前端之家浏览:6981评论:0
关键词:js

HTML元素可以在jquery hide()函数的帮助下隐藏,或者也可以通过在css中使设置visibility:hidden来轻松隐藏。那么如何使用jquery找到这个隐藏元素的高度?

每个HTML元素定义了两种高度,即元素的innerHeight和outerHeight:

1、innerHeight:当不考虑所选元素的边框宽度时,会考虑此高度。

2、outerHeight:当考虑所选元素的边框宽度时,将考虑此高度。

在jQuery中可以使用innerHeight()和outerHeight()方法来分别获取元素这两种高度。下面就通过示例来看看这两种方法如何使用。

示例1:使用innerHeight()方法计算隐藏元素的innerHeight

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style> 
    div { 
        width: 310px; 
        height: 80px; 
        font-weight: bold; 
        color: green; 
        font-size: 25px; 
        border: 1px solid green; 
        visibility: hidden; 
    } 
    body { 
        border: 1px solid green; 
        padding: 10px; 
        width: 300px; 
    } 
</style> 

</head>

<body> 
    <div></div> 
    <p id="demo">这里将显示隐藏的“div”元素的高度。</p> 
    <button id="btn1">Submit</button> 
</body>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script> 
    $(document).ready(function() { 
        $("#btn1").click(function() { 
            var demo = $("div").innerHeight(); 
            $("#demo").text(demo); 
        }); 
    }); 
</script>
</html>

示例2:使用outerHeight()方法计算隐藏元素的outerHeight

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style> 
    div { 
        width: 310px; 
        height: 80px; 
        font-weight: bold; 
        color: green; 
        font-size: 25px; 
        border: 1px solid red; 
        visibility: hidden; 
    } 
    body { 
        border: 1px solid red; 
        padding: 10px; 
        width: 300px; 
    } 
</style> 

</head>

<body> 
    <div></div> 
    <p id="demo">这里将显示隐藏的“div”元素的高度。</p> 
    <button id="btn1">Submit</button> 
</body>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script> 
    $(document).ready(function() { 
        $("#btn1").click(function() { 
            var demo = $("div").outerHeight(); 
            $("#demo").text(demo); 
        }); 
    }); 
</script>
</html>

您的支持是我们创作的动力!
温馨提示:本文作者系 ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://www.jiangweishan.com/article/js41123211421.html

网友评论文明上网理性发言 已有0人参与

发表评论: