当前位置: 代码迷 >> JavaScript >> 为什么我的函数使用javascript不能完全显示div的高度?
  详细解决方案

为什么我的函数使用javascript不能完全显示div的高度?

热度:18   发布时间:2023-06-03 18:09:56.0

为什么我的函数使用javascript不能完全显示div的高度?

我尝试了我的代码但是没有用,我该怎么做?

<script type="text/javascript">
$(document).ready(function(){
    var elmHeight, elmMargin;
    if (document.all) { // IE
        elmHeight = document.getElementById(divxx).currentStyle.height;
        elmMargin = parseInt(document.getElementById(divxx).currentStyle.marginTop, 10) + parseInt(document.getElementById(divxx).currentStyle.marginBottom, 10) + "px";
    }
    else { // Mozilla
        elmHeight = document.defaultView.getComputedStyle(document.getElementById(divxx), '').getPropertyValue('height');
        elmMargin = parseInt(document.defaultView.getComputedStyle(document.getElementById(divxx), '').getPropertyValue('margin-top')) + parseInt(document.defaultView.getComputedStyle(document.getElementById(divxx), '').getPropertyValue('margin-bottom')) + "px";
    }
    alert("Height=" + elmHeight + "\nMargin=" + elmMargin);
});
</script>

<style type="text/css">
#divxx {
    height:20px;
    margin:7px;
} 
</style>

<div id="divxx">TEST AREA</div>

您已经说过,它不显示警报,这几乎可以肯定意味着在某处存在语法或运行时错误。 浏览器的调试器可以告诉您在哪里。

您也太努力了。 :-)由于您已经在使用jQuery,为什么不 ?

var eleHeight = $("#divxx").outerHeight();

如果由于其他原因您确实需要该保证金信息:

var $div = $("#divxx");
var eleHeight = $div.outerHeight();
var eleMargin =
    parseInt($div.css("margin-top"), 10) +
    parseInt($div.css("margin-bottom"), 10);

为您处理整个.currentStylegetComputedStyle事情。

现场示例

 var $div = $("#divxx"); var eleHeight = $div.outerHeight(); var eleMargin = parseInt($div.css("margin-top"), 10) + parseInt($div.css("margin-bottom"), 10); alert("eleHeight = " + eleHeight + ", eleMargin = " + eleMargin); 
 #divxx { height: 20px; margin: 7px; } 
 <div id="divxx">TEST AREA</div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 

  相关解决方案