如何捕获DIV的css属性的高度?例如'身高'。这是HTML。我正在使用jquery插件高度
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>The HTML5 Herald</title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.6.1.min.js'> </script>
<script type='text/javascript' src='http://orlandovisitornetwork.com/wp- includes/js/jquery/jquery.js?ver=1.6.1'></script>
<script type="text/javascript"></script>
</head>
<body>
<div id="main" class='test'>
This is just a test
</div>
<script type="text/javascript">
window.onload=function()
{
var height = $("test").height();
if (height > 0px)
{
alert("DIV Height is" + 'height');
}
};
</script>
</body>
</html>
这是css。当然这是非常简化的版本。
.test {
height: 500px;
}
答案 0 :(得分:2)
这就是window.getComputedStyle
的用途。在你的情况下:
var height = window.getComputedStyle(document.getElementById("main")).height
(ID比类名更可靠。如果只有其中一个,则不应使用类名。)
答案 1 :(得分:1)
要选择一个类,选择器需要以句点开头,如下所示。并且不应引用变量:
$(function() {
var height = $('.test').height();
if (height > 0) {
alert("DIV Height is : " + height);
}
});
答案 2 :(得分:0)
<script type="text/javascript">
window.onload=function()
{
var height = $("test").height();
if (height > 0px)
{
alert("DIV Height is" + 'height');
}
};
</script>
小心点。方法height()
会返回一个数字,您将其与0px
进行比较,没有引号,这不是字符串,数字也不是变量,它可能会计算为null
或{{ 1}}。因此,您的比较将永远不会成立,并且块中的代码将永远不会被执行。
这种方法可能效果很好,你只是做了错误的比较。尝试将undefined
与数字进行比较。