使用JavaScript读取CSS值 [英] Reading CSS value using JavaScript
本文介绍了使用JavaScript读取CSS值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这有效:
<div id="hello" style="width:100%;"></div>
<script>
window.onload = function(){
alert(document.getElementById("hello").style.width);
};
</script>
此操作不有效:
<div id="hello"></div>
<style>
div#hello{
width:100%;
}
</style>
<script>
window.onload = function(){
alert(document.getElementById("hello").style.width);
};
</script>
- 我也尝试过正确放置head标记中的css样式定义不起作用
- 我尝试定义了一个javascript函数,而不是调用window.onload,没有起作用
最糟糕的是,如果我使用javascript设置宽度:
strangest thing is, if I set the width using javascript:
alert( document.getElementById("hello").style.width );
document.getElementById("hello").style.width = "25%";
alert(document.getElementById("hello").style.width );
这会起作用。第一个警报将显示空白警报,然后第二个警报将显示 25%
It would work. The first alert would show a blank alert, then the second alert will show "25%"
推荐答案
您无法访问尚未使用Javascript设置的方式。您需要使用 getComputedStyle
,请参见 https ://developer.mozilla.org/en/DOM/window.getComputedStyle
在MSIE上,其工作原理有所不同。
You cannot access CSS properties that way that have not been set using Javascript. You need to use getComputedStyle
, see https://developer.mozilla.org/en/DOM/window.getComputedStyle
On MSIE this works differently.
这篇关于使用JavaScript读取CSS值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文