0

如何捕获 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;
}
4

3 回答 3

2

window.getComputedStyle就是为了。在你的情况下:

var height = window.getComputedStyle(document.getElementById("main")).height

(ID 比类名更可靠。如果只有一个类名,则不应使用类名)

于 2012-12-10T21:31:20.493 回答
1

要选择一个类,选择器需要以句点开头,如下所示。并且变量不应该被引用:

$(function() {
    var height = $('.test').height();
    if (height > 0) {
          alert("DIV Height is : " + height);
    }
});
于 2012-12-10T21:31:36.957 回答
0
<script type="text/javascript">  
window.onload=function()
  {
    var height = $("test").height();

      if (height > 0px)
    {
      alert("DIV Height is" + 'height');
    }
  };
</script>

那里要小心。该方法height()返回一个数字,您将它与 进行比较0px,没有引号,它不是字符串也不是数字也不是变量,它可能评估为nullor undefined。因此,您的比较永远不会成立,并且块中的代码将永远不会被执行。

该方法可能运行良好,您只是进行了错误的比较。尝试比较height一个数字。

于 2012-12-10T21:42:47.100 回答