jQuery How to Get Element's Margin and Padding?

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

    This works for me:

    var tP = $("img").css("padding").split(" ");
    var Padding = {
        Top: tP[0] != null ? parseInt(tP[0]) : 0,
        Right: tP[1] != null ? parseInt(tP[1]) : (tP[0] != null ? parseInt(tP[0]) : 0),
        Bottom: tP[2] != null ? parseInt(tP[2]) : (tP[0] != null ? parseInt(tP[0]) : 0),
        Left: tP[3] != null ? parseInt(tP[3]) : (tP[1] != null ? parseInt(tP[1]) : (tP[0] != null ? parseInt(tP[0]) : 0))
    };
    

    Result example:

    Object {Top: 5, Right: 8, Bottom: 5, Left: 8}
    

    To make a total:

    var TotalPadding = Padding.Top + Padding.Right + Padding.Bottom + Padding.Left;
    
    0 讨论(0)
  • 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());
    }
    
    0 讨论(0)
提交回复
热议问题