【问题标题】:jQuery .height() wrong in SafariSafari 中的 jQuery .height() 错误
【发布时间】:2016-04-06 12:30:53
【问题描述】:

我在 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:

<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());

我将所有这些都放入了一个代码笔中: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 中有效,但在我的实际情况中无效(使用另一张图片)。除此之外,整个事情都是响应式的,所以我还是想省略这些属性。

顺便说一句:原始图像都是 330x330 像素(即所有的宽高比都是 1:1),但它们在较小的屏幕上按比例缩小。

非常感谢您的解决方案...

【问题讨论】:

  • 试试 outerHeight(true) 这实际上可能有帮助。
  • 我也试过了 - 没有帮助......
  • 你能写出 Jquery 在所有浏览器中记录的值吗?
  • 我在所有这些浏览器中都打开了该页面 - 你是这个意思吗?
  • 不,我的意思是如果你能把控制台日志的值写在这里,这样我们可能会有一些可用的数据。

标签: javascript jquery html css safari


【解决方案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());  
});

您可以参考修改后的代码here

【讨论】:

  • 我在 windows 上的 chrome、firefox 和 safari 中检查过这个。
  • 非常感谢您的回答 - 它解决了我的问题!事实上,单独的loadfunction 已经足够了,我不需要更改任何height 设置。我只能在 10 小时后奖励赏金,所以我必须等待,但我会做到的。
  • @Developer107 也许你可以帮助我。看看这个:stackoverflow.com/questions/58314988/…
猜你喜欢
  • 2012-05-22
  • 1970-01-01
  • 2016-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-24
  • 2021-05-14
  • 1970-01-01
相关资源
最近更新 更多