Unable to get value of margin property from result getComputedStyle

前端 未结 4 1977
慢半拍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:13
    var elem = document.getElementById("your-div");
    if (elem.currentStyle) {
        var margin = elem.currentStyle.margin;
    } else if (window.getComputedStyle) {
        var margin = window.getComputedStyle(elem, null).getPropertyValue("margin");
    }
    
    alert(margin);
    

    you can use this shim,works for all browsers:refer this

    use currentStyle for Internet Explorer.

    use getComputedStyle for other browsers

    0 讨论(0)
  • 2020-12-05 01:16

    I tried something like this and it is worKing for me in all browsers

    var elem = document.createElement('div');
    
    var t=document.createTextNode('M')
    elem.appendChild(t);
    document.body.appendChild(elem);
    
    var myfontSize = getStyle(elem,"fontSize")
    alert(myfontSize)
    
    function getStyle(elem,prop){
    if (elem.currentStyle) {
    var res= elem.currentStyle.margin;
    } else if (window.getComputedStyle) {
    if (window.getComputedStyle.getPropertyValue){
    var res= window.getComputedStyle(elem, null).getPropertyValue(prop)}
    else{var res =window.getComputedStyle(elem)[prop] };
    }
    return res;
    }
    
    0 讨论(0)
  • 2020-12-05 01:17

    Getting an attribute of this interface is equivalent to calling the getPropertyValue method of the CSSStyleDeclaration interface

    http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration

    The problem as David Flanagan precised in 'Javascript the definitive guide' is about computed styles only :

    • Shortcut properties are not computed, only the fundamental properties that they are based on. Don’t query the margin property, for example, but use marginLeft, marginTop, and so on.

    And here's a stackoverflow answer to back this up.

    0 讨论(0)
  • 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

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