detecting true border, padding and margin from Javascript

前端 未结 3 881
执笔经年
执笔经年 2021-02-04 13:44

Is there a way to detect the true border, padding and margin of elements from Javascript code? If you look at the following code:


    
          


        
3条回答
  •  北恋
    北恋 (楼主)
    2021-02-04 14:08

    With jQuery:

    var $elm = $('.box');
    var hPadding = $elm.outerWidth() - $elm.width();
    var vPadding = $elm.outerHeight() - $elm.height();
    var hBorder = $elm.outerWidth() - $elm.innerWidth();
    var vBorder = $elm.outerHeight() - $elm.innerHeight();
    
    console.log("Horizontal padding & border: ", hPadding);
    console.log("Vertical padding & border: ", vPadding);
    console.log("Horizontal border: ", hBorder);
    console.log("Vertical border: ", vBorder);
    .box{ 
      width: 50%;
      padding:10vw; 
      border:10px solid red; 
    }
    
    

    Your way (but you have to state paddingLeft, paddingRight..not just 'padding' ):

    var elm = $('.box');
    console.log("padding left (PX): ", elm.css("paddingLeft"));
    .box { 
      padding:0 50px 0 5vw; 
      border: 2px solid green; 
      width: 300px; 
      height: 300px; 
      margin-left: 4px;
    }
    
    
    some text here

提交回复
热议问题