jQuery How to Get Element's Margin and Padding?

前端 未结 8 2223
感动是毒
感动是毒 2020-12-02 09:20

Just wondering - how using jQuery - I can get an elements formatted total padding and margin etc ? i.e. 30px 30px 30px 30px or 30px 5px 15px 30px etc

I tried

<
8条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-02 09:44

    jQuery.css() returns sizes in pixels, even if the CSS itself specifies them in em, or as a percentage, or whatever. It appends the units ('px'), but you can nevertheless use parseInt() to convert them to integers (or parseFloat(), for where fractions of pixels make sense).

    http://jsfiddle.net/BXnXJ/

        $(document).ready(function () {
        var $h1 = $('h1');
        console.log($h1);
        $h1.after($('
    Padding-top: ' + parseInt($h1.css('padding-top')) + '
    ')); $h1.after($('
    Margin-top: ' + parseInt($h1.css('margin-top')) + '
    ')); });

提交回复
热议问题