元素宽度/高度的方法 [英] methods for element width/height

查看:75
本文介绍了元素宽度/高度的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:是否存在 getBoundingClientRect window.getComputedStyle 会有所不同的情况在宽度高度

Question: Is there a scenario where getBoundingClientRect and window.getComputedStyle would differ in width or height?

我刚发现一个当元素具有 box-sizing 其中窗口时,IE中的 width (见下文)不一致。 getComputedStyle 返回错误的值。

I just found a inconsistent width (see under) in IE when a element has box-sizing where window.getComputedStyle returns the wrong value.

所以我考虑重写宽度 height 使用来自 getBoundingClientRect 的值,但不确定是否存在失败的情况。

So I thought about overriding just width and height with values from getBoundingClientRect but not sure if there are cases where that would fail.

问题示例(已损坏在IE): http://jsfiddle.net/bwPM8/

Example of the problem (broken in IE): http://jsfiddle.net/bwPM8/

var box = document.querySelector('.box');
var gBCR_width = box.getBoundingClientRect().width; // always 200
var wGCS = window.getComputedStyle(box).width; // 200 some browsers, 160 in IE


推荐答案

在IE浏览器中CSS 填充:10px; 导致溢出,这给你额外的computedStyle大小..

In IE the CSS padding: 10px; cause overflow and that gives you extra size of the computedStyle..

另外IE计算 Borders 与对象分开。

Also IE calculates Borders separately from the object.

这总结了答案,差异为 40px

This sums up the answer with difference of 40px

现在使用溢出:隐藏; 框大小调整:border-box; 导致值变为负值因此将变为200px - 40px = 160px。

Now with overflow:hidden; OR box-sizing: border-box; that cause value go in minus so will become 200px - 40px = 160px.

注意:如果我们删除 overflow:hidden 将不会有任何区别,因为 box-sizing:border-box 导致设计不要从定义的高度和宽度进一步增长。

Note: Here if we remove overflow:hidden will not make any difference as the box-sizing:border-box cause the design not to grow further from defined height and width.

我已经生成另一个 小提琴1 (无填充),它给出了

I have generate another fiddle 1 (without padding) which gives

'computedValue:180px'

'computedValue : 180px'

使用边框:0px 小提琴2 给出结果
与其他浏览器相同..

And with Border:0px the fiddle 2 give results same as in other browser..

我希望这能清除IE中的原因(IE有自己的想法,有时会给开发人员带来痛苦) )

I hope this clears what causes what in IE(IE has its own mind that sometimes cause pain to developers)

这篇关于元素宽度/高度的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆