vue2中el-table在页面右下方时点击右键菜单位置设置

由于el-table的位置有偏移, 当右键点击el-table的行事件时弹出菜单, 但是当点击最右边或者最下边的时候, 菜单会被盖掉, 所以在获取距离的时候减去整个table的偏移距离, 并且要把盖住的菜单的宽和高减去,就能正常显示到页面了. 

 

<div id="menu" class="menuDiv" ref="menuRef">
  <ul class="menuUl">
    <li
      v-for="(item, index) in filteredMenus"
      :key="index"
      @click.stop="infoClick(index, item.operType)"
    >
      {
   
   { item.name }}
    </li>
  </ul>
</div>
<script>
// el-table的右键点击当前行事件
rightClick(row, column, event) {
  //阻止元素发生默认的行为
  event.preventDefault();
  
  if (this.xqArr.length === 0) {
    menu.style.display = "none";
  } else if (this.xqArr.length > 0) {
    // 计算菜单应该放置的位置
    // 获取 el-table 组件的 DOM 元素
    this.tableDom = this.$refs.multipleTable.$el;

    const tableRect = this.TableDom.getBoundingClientRect(); // 获取el-table元素的位置信息
      this.tableRectTop = Math.ceil(tableRect.top); // eltable左边缘距离页面左侧的位置
      this.tableRectLeft = Math.ceil(tableRect.left); // eltable上边缘距离页面顶部的位置
            
    const menuWidth = 100; // 菜单的宽度
    const menuHeight = this.filteredMenus.length * 35; // 菜单的高度
    const menuX = event.clientX - this.tableRectLeft; // 点击的位置减去eltable左边缘距离页面左侧的位置
    const menuY = event.clientY - this.tableRectTop; // 点击的位置减去eltable上边缘距离页面顶部的位置
    const menuRight = menuX + menuWidth; // 菜单在el-table容器里的位置加菜单宽度
    const menuBottom = menuY + menuHeight; // 菜单在el-table容器里的位置加菜单高度
    const overflowX = Math.max(menuRight - this.TableDom.clientWidth + 10, 0); // 点击页面最右边时,菜单会超出页面,此时需要减去table的宽度,+10是滚动条的宽
    const overflowY = Math.max(menuBottom - this.TableDom.clientHeight + 10, 0);

    const menuLeft = menuX - overflowX;
    const menuTop = menuY - overflowY;

    const menu = this.$refs.menuRef.$el;

    // 设置菜单的位置
    menu.style.left = `${menuLeft}px`;
    menu.style.top = `${menuTop}px`;
    // 改变自定义菜单的隐藏与显示;
    menu.style.display = "block";
    menu.style.zIndex = 1000;
  }
},
</script>
<style>
// 单击单元格右键菜单样式
.menuDiv {
  display: none;
  position: absolute;

  .menuUl {
    height: auto;
    width: 100px;
    font-size: 14px;
    text-align: left;
    border-radius: 3px;
    border: none;
    background-color: $menuBg;
    color: #fff;
    list-style: none;
    padding: 0 10px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    li {
      width: 100px;
      height: 35px;
      line-height: 35px;
      cursor: pointer;
      border-bottom: 1px solid rgba(255, 255, 255, 0.47);

      &:hover {
        color: rgb(54, 138, 175);
      }
    }
  }
}
</style>

猜你喜欢

转载自blog.csdn.net/m0_62323730/article/details/130842889