Safari中的jQuery .height()错误
我在Safari中使用jQuery读取DIV
的正确高度时遇到问题。 我使用jQuery("#x").height()
来读出元素的高度。 在实际情况中,我稍后会在页面中使用结果。 它适用于Chrome,Firefox和IE,但不适用于Safari。
以下是我从页面中提取的一些代码,用于演示此问题:
CSS:
#x { position: absolute; top: 0px; margin-top: 80px; right: 54%; width: 40vw; height: auto; max-width: 330px; padding: 10px 3.1vw 16px; background: #ddd; } .y { position: relative; width: 100%; max-width: 330px; height: auto; max-height: 330px; } .y img { width: 100%; height: auto; }
(一些参数看起来多余或奇怪,但我需要它们在我的上下文中,如果我把它们排除在外它不会改变问题)
HTML:
Header
Some text
Some more text...
现在,有了这个jQuery代码,我会得到不同的结果,具体取决于浏览器:
console.log(jQuery("#x").height());
我将所有这些都放入了一个codepen: http ://codepen.io/anon/pen/MyELJV?editors = 1111
如果你在Firefox中加载它,控制台输出是469.如果你在Safari中加载它,它是154.(另外:在Chrome / MacOS和IE11 / Win7中,值为466)。 差异的一小部分是由于不同的默认样式,但主要问题是Safari在获得高度时不考虑图像。
如果尝试了不同的东西(没有解决问题):
- 我尝试使用
innerHeight()
,outerHeight()
和outerHeight(true)
而不是height()
– 没有基本的区别(略有不同的值,但仍然是Safari中的问题)。 - 我将
width=330 heigth=330
为img
标签的属性,它在codepen中工作,但不是在我的实际情况下(使用另一个图像)。 除此之外,整个过程都是响应式的,所以无论如何我都想省略这些属性。
顺便说一句:原始图像都是330x330px(即都具有1:1的宽高比),但它们在较小的屏幕上缩小。
我非常感谢解决方案……
我改变了你的css,以便safari不会改变图像的高度。
#x { position: absolute; top: 0px; margin-top: 80px; right: 54%; width: auto; height: auto; /* max-width: 330px; */ padding: 10px 43px 16px; background: #ddd; } .y { position: relative; width: 100%; max-width: 330px; height: auto; max-height: 330px; } .y img { width: auto; height: auto; }
还可以使用load
函数来获取#x
精确高度。
$(window).load(function(){ console.log($("#x").height()); });
您可以在此处参考更改的代码。