jQuery How to Get Element's Margin and Padding?

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

    If the element you're analyzing does not have any margin, border or whatsoever defined you won't be able to return it. At tops you'll be able to get 'auto' which is normally the default.

    From your example I can see that you have margT as variable. Not sure if're trying to get margin-top. If that's the case you should be using .css('margin-top').

    You're also trying to get the stylization from 'img' which will result (if you have more than one) in an array.

    What you should do is use the .each() jquery method.

    For example:

    jQuery('img').each(function() {
        // get margin top
        var margT = jQuery(this).css('margin-top');
    
        // Do something with margT
    });
    

提交回复
热议问题