【问题标题】:Getting the style of an element获取元素的样式
【发布时间】:2014-07-28 19:38:51
【问题描述】:

我想用 JavaScript 获取元素的高度,但我想要这个值,即使它应用在 <style> 标记中,而不仅仅是内联。

   <style>
     #test{height:100px;}
   </style>
   <div id="test"></div>
   <script>

   alert(document.getElementById("test").style.height);


   <script>

上面的alert 没有显示任何内容,因为它只是获取内联样式,而不是整个样式。如何访问元素的所有样式?

【问题讨论】:

标签: javascript html css styles


【解决方案1】:

如果您想要完整的计算样式,请使用:

window.getComputedStyles(document.querySelector('#test'));

然后去:

window.getComputedStyles(document.querySelector('#test')).height;

这将为您提供以 px 为单位的高度,即使您指定了百分比高度。

另外,你可以使用:

document.querySelector('#test').clientHeight;

不过,这将包括填充,这取决于您的需要。阅读更多:

https://developer.mozilla.org/en-US/docs/Web/API/Element.clientHeight

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-24
    • 2021-03-12
    • 1970-01-01
    • 2014-02-24
    • 2014-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多