【问题标题】:get value from css using document.getElementById().style.height javascript使用 document.getElementById().style.height javascript 从 css 中获取值
【发布时间】:2011-12-11 18:30:47
【问题描述】:

请提供关于这个谜团的见解。

我正在尝试通过

从 div 框中获取高度值
var high = document.getElementById("hintdiv").style.height; 
alert(high);

如果属性包含在 div 标签中,我可以得到这个值,但如果属性是在 css 部分中定义的,它会返回一个空白值。

这很好,它显示 100px 作为值。可以访问该值。

<div id="hintdiv" style="height:100px; display: none;">
.
.
var high = document.getElementById("hintdiv").style.height; 
    alert(high); 

这不好,它显示一个空白的警报屏幕。该值实际上是 0。

#hintdiv
{
height:100px
display: none; 
}

<div id="hintdiv">
.
.
var high = document.getElementById("hintdiv").style.height; 
    alert(high); 

但无论是在标签中还是在 css 部分中,访问/更改“display:none”属性都没有问题。 div 框通过两种属性定义方法(在标签内或在 css 部分中)正确显示。

我也尝试通过其他变体访问该值,但没有运气

document.getElementById("hintdiv").style.height.value  ----> undefined
document.getElementById("hintdiv").height ---->undefined
document.getElementById("hintdiv").height.value  ----> error, no execution

有什么办法吗?

TIA。

【问题讨论】:

标签: javascript


【解决方案1】:

这是因为,当您使用document.getElementById("hintdiv").style.height; 时,您正在访问标记的style 属性。如果该属性不存在,那么您将得不到任何值。

相反,您应该在 IE 中使用 currentStyle 对象,在其余 Web 浏览器中使用 getComputedStyle() 函数。

【讨论】:

    【解决方案2】:

    你的 CSS 语法错误,应该是 height:100px; 而不是 height:100px。注意分号。

    【讨论】:

      【解决方案3】:

      你应该考虑使用 jQuery 代替...它将简化为 $('#hintDiv').height() 并且它总是返回 div 的实际宽度。

      【讨论】:

      • 感谢 DevIT,我需要买一本 jquery 书。
      • 嗨 epascarello !很高兴我能帮上忙……但是要学习 jQuery,你并不绝对需要一本书,只需尝试 jQuery 网站上的教程:docs.jquery.com/Tutorials
      猜你喜欢
      • 2011-09-14
      • 2016-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-30
      • 1970-01-01
      相关资源
      最近更新 更多