Unable to get value of margin property from result getComputedStyle

前端 未结 4 1979
慢半拍i
慢半拍i 2020-12-05 00:37

The result of a getComputedStyle contains a property named \"margin\", but the property is always an empty string (\"\") in Mozilla Firefox or Appl

4条回答
  •  攒了一身酷
    2020-12-05 01:25

    The getComputedStyle() function should not evaluate the values of shorthand properties (such as margin, padding), only longhand properties (such as margin-top, margin-bottom, padding-top). In the case of shorthand properties it should only return an empty string.

    var el = document.body.appendChild(document.createElement('div'));
    el.style.margin = '2px';
    var computed = getComputedStyle(el);
    
    var longhands = ['margin-top', 'margin-bottom', 'margin-left', 'margin-right'];
    longhands.forEach(function(e) { console.log(e + ': ' + computed.getPropertyValue(e)) });

    In addition, you can take a look at this link for a cross-browser solution, which uses currentStyle for internet explorer

提交回复
热议问题