开发者

Can jquery return height of an element as a percentage?

开发者 https://www.devze.com 2023-01-11 07:22 出处:网络
$(\'#my_div\').height(\'50%\') will set the 开发者_开发问答height but how can you retrieve the div\'s current height as a percentage?You can use .height(), which returns just the number (i.e, without

$('#my_div').height('50%') will set the 开发者_开发问答height but how can you retrieve the div's current height as a percentage?


You can use .height(), which returns just the number (i.e, without the unit symbol). Perfect for percentage, which of course needs no units. From the docs:

The .height() method is recommended when an element's height needs to be used in a mathematical calculation.

So you can try something like this:

var height_pct = Math.round( 
    $('#my_div').height() / 
    $('#my_div').parent().height() * 100
    );


you can convert get height in px and convert them to percenatge

1em = 12pt = 16px = 100%


So Simple $("#eleid")[0].style.width


Try to hide the element you'll get it's percentage value.

<div id="a" style ="height: 300px; background: green; display: none;">
    a
    <div id="b" style ="height: 10%; background: blueviolet;">
        b
    </div>
    <div id="c" style ="height: 20%; background: cornflowerblue;">                        
        c
    </div>        
</div>
<script>
$(document).ready(function(){
    // height outside of event     
    $("#a").append($("#a").height());
    $("#b").append($("#b").height());
    $("#c").append($("#c").height());

    // height inside of event               
    $("*").click(function(){                
        $("#a").css("display", "block");
        $("#a").append($("#a").height());
        $("#b").append($("#b").height());
        $("#c").append($("#c").height());
    })
}) 
</script>

Notice that the value is different inside an event function.

Addition Notes:

The value reported by .height() is not guaranteed to be accurate when the element or its parent is hidden. To get an accurate value, ensure the element is visible before using .height(). jQuery will attempt to temporarily show and then re-hide an element in order to measure its dimensions, but this is unreliable and (even when accurate) can significantly impact page performance. This show-and-rehide measurement feature may be removed in a future version of jQuery.

Source: jQuery height()


Based on the other answer, for a fixed div like a panel, that is what worked for me:

    var h = Math.round(
        $('#my_div').height() /
        $(window).height() * 100
    );
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号