Javascript 如何获取元素';CSS类中的属性集
我想读取元素的高度和宽度Javascript 如何获取元素';CSS类中的属性集,javascript,css,Javascript,Css,我想读取元素的高度和宽度 <style type="text/css"> .big { height: 100px; width: 100px } </style> <div id="box1" style="width:50px; height=50px;"></div> <div id="box2" class="big"></div> .大{ 高度:100px; 宽
<style type="text/css">
.big {
height: 100px;
width: 100px
}
</style>
<div id="box1" style="width:50px; height=50px;"></div>
<div id="box2" class="big"></div>
.大{
高度:100px;
宽度:100px
}
对于box01
我可以使用height=getElementById(“box01”).style.height
-这很好
但是对于box02,它不起作用。它不返回任何内容。- (适用于现代浏览器)
- (适用于旧IE版本)
- 如果您使用的是mootools,您必须随身携带
$('box2').getHeight().toInt();
只是为了得到int值(不带'px')
否则在jquery中
$('.box2').height();
我会成功的
如果你想使用默认的javascript
var elem1 = document.getElementById("box2");
var style = window.getComputedStyle(elem1, null);
您可以使用
window.getComputedStyle()
获取任何html元素的实际维度,如下所示:
var elem1 = document.getElementById("box01");
var height = window.getComputedStyle(elem1, null).getPropertyValue("height");
看。我建议你调查一下。这是一段非常有用的代码 要获取css属性,请执行以下操作:
var box1Height = $('#box1').css('height');
#box1让jquery知道您想要对ID为box1的HTML对象执行操作。这就是#符号的含义。在中,您将使用
窗口.getComputedStyle
或元素.currentStyle
(取决于哪个浏览器)。旧版本的IE需要currentStyle
下面是一个快速的可互操作垫片,它将使您可以在所有浏览器中使用一个全局函数,而无需包含像jQuery这样的整个库:
//must be executed on or after the domready event, since it (may) require document.body to be non-null
var getComputedStyle = function() {
var func = null;
if (document.defaultView && document.defaultView.getComputedStyle) {
func = document.defaultView.getComputedStyle;
} else if (typeof(document.body.currentStyle) !== "undefined") {
func = function(element, anything) {
return element["currentStyle"];
};
}
return function(element, style) {
return func(element, null)[style];
}
}();
//and use like so:
getComputedStyle(document.getElementById("foo"), "display"); //might return "inline-block"
从本文复制的代码:。谷歌搜索还可以找到许多其他类似的方法来实现这一点。如果您想要元素的高度,那么读取clentHeight或offsetHeight属性可能比css更为重要。您使用的是什么框架?jquery/mootools/随便什么?T.J.Crowder:谢谢你的编辑,尽管我也几乎立刻注意到了我的打字错误。这通常是这里的惯例,所以如果你想要一个使用框架的答案,你可以在你的问题中包含框架的关键字。如果您没有包含任何框架作为关键字,那么您需要的是一个简单的javascript解决方案。
//must be executed on or after the domready event, since it (may) require document.body to be non-null
var getComputedStyle = function() {
var func = null;
if (document.defaultView && document.defaultView.getComputedStyle) {
func = document.defaultView.getComputedStyle;
} else if (typeof(document.body.currentStyle) !== "undefined") {
func = function(element, anything) {
return element["currentStyle"];
};
}
return function(element, style) {
return func(element, null)[style];
}
}();
//and use like so:
getComputedStyle(document.getElementById("foo"), "display"); //might return "inline-block"