我DIV
在Safari中使用jQuery读取正确高度时遇到问题。我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:
<div id="x">
<h2>Header</h2>
<div class="y">
<img src="https://placehold.it/330" alt="my image">
</div>
<p class="z"><span>Some text</span><br>Some more text...</p>
</div>
现在,使用此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,以便野生动物园不会更改图像的高度。
#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());
});
您可以在此处引用更改的代码。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句