繁体   English   中英

如何检查div是否具有液体/自动高度?

[英]How to check if a div has a liquid / auto height?

我需要检查javascript(或者jQuery)如果div有css属性height:auto ,或者检查这个div是否没有设置任何高度? 但实际上浏览器就像它一直计算div的当前高度然后将它分配给该div。 所以实际上div总是有一个高度设置,即使在css我们说div必须是height:auto 我怎样才能做到这一点?

这是我的解决方案,我在我的jQuery插件ScaleText中成功实现了:

  function checkAutoHeight(el) {
    // Get the original height of the parent.
    var origHeight = $(el).parent().outerHeight();

    // Create a 1px bump in the size of the element you are checking.
    var tester = $(el).append('<div class="scaleTextHeightCheck" style="display: block; height: 1px; width: 1px; content: \'\';""></div>');

    // Check to see if the parent increased by 1px as a result of the bump.
    var newHeight = $(el).parent().outerHeight();

    // Cleanup.
    $('.scaleTextHeightCheck').detach();

    // Return the result.
    return (origHeight < newHeight);
  }

昨天我正在努力解决这个问题,但我找到了一个有效的黑客。

插入

$.fn.isAuto = function(){
    var originalHeight = this.height();
    this.append('<div id="test"></div>');
    var testHeight = originalHeight+500;
    $('#test').css({height: testHeight});
    var newTestHeight = $('#test').height();
    var newHeight = this.height();
    $('#test').remove();
    if(newHeight>originalHeight){
        return true;    
    }
    else{
        return false;
    }
};

这是一个演示插件的小提琴

基本上,插件在原始元素中添加一个div,并使其高度大于原始元素。 如果原始元素的新高度大于原始高度,则元素增长,高度为auto。

检查以下某项的值,看看它们是否可以帮助您

document.getElementById ( 'divid' ).style.height
$('#divid').css ( 'height' )
$('#divid')[0].style.height

显然, divid是你的div的id

你可以使用currentStyle属性在IE中完成它

var height= document.getElementById('divid').currentStyle.height;

不幸的是,你不能在任何其他浏览器中做到这一点(我认为这是我唯一喜欢的IE)。 实际上你可以做到,但不是直接的。

其他浏览器的方法如下:

首先,您必须检查内联高度属性(它可能是一个允许使用它的表),然后您必须找到内联样式属性并检查它是否已定义高度。 然后,您必须遍历文档中的所有样式,并检测更严格的加工样式,并检查是否存在另一个不太严格但具有!important修饰符的样式。

正如您所看到的,这不是一个简单的过程,因此在其他浏览器中可以实现,但并不容易。 如果您只针对IE,那么您就完成了:-)

祝好运!

在jQuery $('#mydiv').css('height'); 会给你<div id="mydiv"></div>的高度

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM