如何捕获 DIV 的 css 属性的高度?例如"身高"



如何捕获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;
}
这就是

window.getComputedStyle的用途。在您的情况下:

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

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

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

$(function() {
    var height = $('.test').height();
    if (height > 0) {
          alert("DIV Height is : " + height);
    }
});
<script type="text/javascript">  
window.onload=function()
  {
    var height = $("test").height();
      if (height > 0px)
    {
      alert("DIV Height is" + 'height');
    }
  };
</script>

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

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

相关内容

最新更新