【问题标题】:Get div size with JS after CSS3 transformationCSS3转换后用JS获取div大小
【发布时间】:2012-11-19 19:54:07
【问题描述】:

我试图在对其应用一个/几个 CSS3 转换后获取 JavaScript 中元素的高度。

#transformed{
    transform:scale(.5);
}

不幸的是,JQuery 的 outerHeight 似乎并没有天真地做到这一点。

$('#after').outerHeight(); //not affected by the transformation

示例: http://jsfiddle.net/mQ2nT/

【问题讨论】:

  • Inspector 给出了相同的结果。
  • 鉴于@Musa 的评论,您可能不太走运 - 除非您想开始手动解析 CSS3 转换规则。
  • +1 好问题。对答案的投票有很多,但对真正有趣的问题却没有投票。

标签: javascript jquery html css


【解决方案1】:

您可以使用getBoundingClientRect获取变换后的尺寸和位置。

只需转换您的元素,然后:

$('#after')[0].getBoundingClientRect();
// note the [0], the function is DOM not jQuery's.

最好的是,这也会在您应用每次转换后返回正确的位置和尺寸。

您可以随意使用rotateskewtranslate 以及 CSS 提供的所有其他内容。 gBCR 会处理它。

【讨论】:

  • 非常好!没想到。
  • @Musa:出于好奇,有没有办法查询getBoundingClientRect,包括边距?在 Chrome 中运行小提琴并对 div 应用边距时,jquery 可以使用 outerHight(true) 包含边距,但它们似乎被 getBoundingClientRect.height() 属性忽略。见这里:jsfiddle.net/mQ2nT/4
  • @FrançoisWahl,没有。边距不是边界框的一部分。
  • 根据this article,如果使用getBoundingClientRect in IE7 or older, the returned object contains the coordinates in physical pixel size, while from version 8, it contains the coordinates in logical pixel size. 这似乎只在我收集的缩放时才重要。 +1 @psycketom 虽然我认为 getBoundingClientRect 也是我个人的首选选项(现在我了解了它),除非我需要包含边距或出于某种原因必须支持放大 IE7 或更早版本。
  • @FrançoisWahl,CSS3 转换和 IE
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-13
  • 2013-02-12
  • 2013-06-09
  • 2012-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多