jQuery How to Get Element's Margin and Padding?

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

    I've a snippet that shows, how to get the spacings of elements with jQuery:

    /* messing vertical spaces of block level elements with jQuery in pixels */
    
    console.clear();
    
    var jObj = $('selector');
    
    for(var i = 0, l = jObj.length; i < l; i++) {
      //jObj.eq(i).css('display', 'block');
      console.log('jQuery object:', jObj.eq(i));
      console.log('plain element:', jObj[i]);
    
      console.log('without spacings                - jObj.eq(i).height():         ', jObj.eq(i).height());
      console.log('with padding                    - jObj[i].clientHeight:        ', jObj[i].clientHeight);
      console.log('with padding and border         - jObj.eq(i).outerHeight():    ', jObj.eq(i).outerHeight());
      console.log('with padding, border and margin - jObj.eq(i).outerHeight(true):', jObj.eq(i).outerHeight(true));
      console.log('total vertical spacing:                                        ', jObj.eq(i).outerHeight(true) - jObj.eq(i).height());
    }
    

提交回复
热议问题