简体   繁体   English

!important和display:none和.height()怪异

[英]!important and display:none and .height() weirdness

I discovered something weird yesterday when working with a piece of JS code. 昨天我在使用一段JS代码时发现了一些奇怪的东西。 I had a div that was hidden ( display:none ), and I was using the height of it in some calculations in JS. 我有一个隐藏的divdisplay:none ),我在JS的一些计算中使用它的高度。 This was all working fine, until I added my "hidden" class (which has display:none !important ). 这一切都很好,直到我添加了我的“隐藏”类( display:none !important )。

Suddenly the height was always 0 . 突然,高度始终为0 There were no other changes than !important on the display. 在显示屏上没有其他任何变化!important

After some digging I've narrowed the problem down to something I find rather weird: 经过一番挖掘,我把问题缩小到了一些我觉得很奇怪的东西:

#b { display:none; }            /* reported height is 36 */
#c { display:none !important; } /* reported height is 0  */

I've created a very basic JSFiddle to isolate this. 我创建了一个非常基本的JSFiddle来隔离它。 It also uses vanilla JS to get height, which seems to work just fine / as expected. 它还使用香草JS来获得高度,这看起来很好/正如预期的那样。

It seems like jQuery incorrectly reports height on invisible DIVs, and that !important behaves correctly. 似乎jQuery错误地报告了不可见DIV的高度,而且!important行为正确。

Is this a bug in jQuery? 这是jQuery中的错误吗?

I dont think this is a bug in jQuery, jQuery sets display to block for a fraction of a second to calculate height , when you set !important even that is ovverriden, thats all. 我不认为这是jQuery中的一个错误,jQuery设置display block一小段时间来计算height ,当你设置!important甚至是ovverriden,那就是全部。

I guess we need some more explanation 我想我们需要更多解释

There is basically no way to get the height of an element from DOM if it doesn't have any height. 目前基本上没有办法让height从DOM元素,如果它不具有任何高度。 So when display is none , the height is nonexistent or zero . 因此,当displaynoneheight不存在或zero

In jQuery if display is none , we can just set display to block for a fraction of a second to get the height , during this inline style is altered as usually done by jQuery. 在jQuery中,如果displaynone ,我们可以将display设置为block一小段时间以获得height ,在此inline样式中通常由jQuery更改。

<div id="something" style="display:block">/div>

And then height is taken, but at this time if you have set display:none!important in css this inline style wont work, and height calculated becomes zero . 然后是height ,但是此时如果你在css中设置了display:none!important ,这个内联样式将不起作用,并且height计算变为zero

In my personal opinion its always better not to use !important as it makes your code/presentation hard to read. 在我个人看来,最好不要使用!重要因为它使您的代码/演示文稿难以阅读。 Css usually has multitude of ways to override styles. Css通常有多种方式来覆盖样式。

If you still want to proceed, an inline !important might override your style, and calculate the height by yourself using the jQuery show for a second technique, or just override the jQuery function to calculate height :) 如果您仍想继续,内联!important可能会覆盖您的样式,并使用jQuery show为第二种技术自己计算高度,或者只是覆盖jQuery函数来计算高度:)

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

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