jQuery How to Get Element's Margin and Padding?

前端 未结 8 2220
感动是毒
感动是毒 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:30

    var bordT = $('img').outerWidth() - $('img').innerWidth();
    var paddT = $('img').innerWidth() - $('img').width();
    var margT = $('img').outerWidth(true) - $('img').outerWidth();
    
    var formattedBord = bordT + 'px';
    var formattedPadd = paddT + 'px';
    var formattedMarg = margT + 'px';
    

    Check the jQuery API docs for information on each:

    • outerWidth
    • innerWidth
    • width

    Here's the edited jsFiddle showing the result.

    You can perform the same type of operations for the Height to get its margin, border, and padding.

提交回复
热议问题