封装弹框组件

229 阅读1分钟

弹框

主要总结一下最近写弹框遇到的问题及解决

  • 弹框分为三部分 遮罩层 + 弹框 + 内容
  • 主要代码如下:
<template>
<!--   遮罩层 -->
  <div class="mask">
<!--     弹框 -->
    <div class="dialog">
      <div class="header">header</div>
<!--       以下内容部分可以使用 <slot></slot> 由父组件传内容 -->
      <div>nihao</div>
      <div>nihao</div>
      <div>nihao</div>
      <div>nihao</div>
      <div>nihao</div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {};
  },
};
</script>

<style>
.mask {
  height: 100%;
  width: 100%;
  position: fixed;
  top: 0;
  left: 0;
  background-color: #f6f6f6;
}

.dialog {
  max-height: 10%;
  width: 100%;
  position: fixed;
  overflow-y: scroll;
  bottom: 0;
  background-color: #fff;
  z-index: 10;
}

.header {
}
</style>

遇到的问题:

  • 如果主页面高度超过100vh,滑动弹框至顶部或底部其背景页面也会滑动造成滚动穿透。

解决方式: 获取根元素,定义can() stop()方法控制body元素的滚动

// 禁止页面滚动
stopScroll() {
  let body = document.getElementsByTagName('body')[0]
  let obj = {}
  obj.can = () => {
    body.style.overflow = 'visible'
    body.style.height = 'auto'
  }
  obj.stop = () => {
    body.style.overflow = 'hidden'
    body.style.height = '100%'
  }
  return obj
},

在data中定义变量保存返回的obj,需要的时候调用上面的两个方法

this.xxx.stop()    //禁止
this.xxx.can()     //可滑动

场景问题:

  1. 天降红包的弹框内部有的时候滑不动,控制台查看元素,滚动的元素被遮挡(调整z-index),滚动失效
  2. 弹框的圆角问题
  3. 样式问题

这里是position定位的问题

position : sticky | fixed | absolute | relative | static

脱离文档流 sticky fixed absolute

思路:

/* 最外层的box */
position:fixed;
top:xxpx;
bottom:xxpx;
/* 下面对于脱离文档流的元素失效 */
overflow:hidden;  

/* 内部的拼接元素 */
position:absolute | relative;
top:xxxpx;
left:xxxpx;