Javascript element style

后端 未结 4 1035
名媛妹妹
名媛妹妹 2021-01-12 09:14

I\'m curious why this one

fdsfsd
.overlay{ width: 100px; height: 200px; background-color:red; }
相关标签:
4条回答
  • 2021-01-12 09:35

    The .style is inline style="width:100px;" only...

    If it's in CSS (rather than inline) you need getComputedStyle -

    https://developer.mozilla.org/en/docs/Web/API/window.getComputedStyle

    0 讨论(0)
  • 2021-01-12 09:44

    As noted elsewhere, the problem is that HTMLElement.style retrieves the values from the style attribute of the element; as you're setting your style with CSS, you need to instead use window.getComputedStyle(element, null).width:

    var elem = document.getElementsByClassName("overlay")[0],
      width = window.getComputedStyle(elem, null).width;
    
    console.log(width);
    .overlay {
      width: 100px;
      height: 200px;
      background-color: red;
    }
    <div class="overlay">
      fdsfsd
    </div>

    References:

    • HTMLElement.style.
    • window.getComputedStyle().
    0 讨论(0)
  • 2021-01-12 09:48

    The JavaScript .style only relates to inline styles on the element.

    See Documentation.

    If you want to get the width of an element you should use offsetWidth.

    document.getElementsByClassName("overlay")[0].offsetWidth
    

    http://jsfiddle.net/9kwap3zy/7/

    0 讨论(0)
  • 2021-01-12 09:58

    The style gives access only to information which is put into elem.style. In your example style doesn’t tell anything about the margin defined in CSS. Use getComputedStyle().

    var computedStyle = getComputedStyle(document.getElementsByClassName("overlay")[0], null)
    
    alert(computedStyle.width);
    

    jsfiddle demo

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