detecting true border, padding and margin from Javascript

前端 未结 3 880
执笔经年
执笔经年 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:05

    the style property can get the styles that are assigned inline like

    <div id="target" style="color:#ffffd;margin:10px">test</div> if you want to get the styles assigned in outer css file or <style/> element, try this:

    var div = document.getElementById("target");
    var style = div.currentStyle || window.getComputedStyle(div);
    display("Current marginTop: " + style.marginTop);
    

    if you are using jQuery, @vsync 's solution is fine.

    0 讨论(0)
  • 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; 
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class='box'></div>

    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;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="box">some text here</div>

    0 讨论(0)
  • 2021-02-04 14:09

    It's possible, but of course, every browser has its own implementation. Luckily, PPK has done all the hard work for us:

    http://www.quirksmode.org/dom/getstyles.html

    0 讨论(0)
提交回复
热议问题