【问题标题】:getBoundingClientRect().width not returning correct widthgetBoundingClientRect().width 没有返回正确的宽度
【发布时间】:2015-12-06 13:57:52
【问题描述】:

我正在尝试获取元素的宽度,但该值始终小于实际宽度。到目前为止,这是我的代码:

this.rightSectionElement = this.$('.sections').eq(1).get(0);
this.rightSectionOffset = this.rightSectionElement.getBoundingClientRect().width;

相关元素上的 CSS 是这样的:

nav{
    position: relative;
    width: 100%;
    height: 100%;
    @include inline-flex();
    flex-wrap: nowrap;
    justify-content: space-between;
    z-index: 1;

    .sections{
              @include flex-value(0 1 auto);
              height: 100%;
              width: auto;
              display: block;
...

这种方法对flexbox排列的元素是不是很好玩?

【问题讨论】:

  • 你有没有发现发生了什么?当我将 getBoundingClientRect() 与 flexbox 一起使用时,宽度会丢失 40 像素,高度会丢失 5 像素。

标签: javascript flexbox


【解决方案1】:

您是否对元素应用了任何边距或边框? getBoundClientRect() 在计算宽度时不考虑边距或边框。

请看这里:https://jsfiddle.net/aprax/t94cj9hh/1/

#container {
  display: flex;
  width: 300px;
  margin: 20px;
  border: 5px;
}
--------------
//Outputs 300
document.write(document.getElementById("container").getBoundingClientRect().width); 

【讨论】:

    猜你喜欢
    • 2017-04-30
    • 1970-01-01
    • 2017-10-03
    • 1970-01-01
    • 2015-12-14
    • 2021-03-19
    • 2021-05-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多