消除BFC对绝对定位的影响

218 阅读1分钟

一、问题起因

//app.vue  
  <div class="app" style="overflow:hidden">
    <g-popover>
      <div>come on</div>
      <g-button slot="reference">click!</g-button>
    </g-popover>
  </div>

//popover.vue

  <div class="popover">
    <div class="content-wrapper">
      <slot></slot>
    </div>
    <slot name="reference"></slot>
  </div>

.popover {
    position: relative;
        .content -wrapper {
        position: absolute;
        bottom: 100%;
        left: 0;
    }
}

加了一行 style="overflow:hidden" 代码那么 .content -wrapper 超出部分就会消失

二、解决方案

常见的方法就是

document.body.appendChild(this.$refs.contentWrapper);

插到body最底部,然后考虑css即可

let { left, top ,height} = this.$refs.triggerWrapper.getBoundingClientRect();
this.$refs.contentWrapper.style.left = left + window.scrollX + "px";
this.$refs.contentWrapper.style.top = top + window.scrollY + "px";

Element.getBoundingClientRect() 方法返回元素的大小及其相对于视口的位置。

DOMRect 示例图

如果你需要获得相对于整个网页左上角定位的属性值,那么只要给top、left属性值加上当前的滚动位置(通过 window.scrollX 和 window.scrollY)。

和offset不一样。