element 表格气泡是如何实现的

前言

很多情况,我们会使用el-input 设置为disabled后来展示数据,比如:
在这里插入图片描述
但是有个情况,当内容过多时,是无法完全显示内容的,虽然我们可以使用el-tooltip 来添加一个气泡,通过气泡显示。
气泡的话其实也有一个问题,添加气泡后,无论内容是否超出,只要鼠标移入时都会显示出气泡。最好的效果其实就是像el-table 那样,当文字溢出时显示省略号,鼠标移入时会显示气泡。

下面我们参考elemnt 的源码来简单封装一个文本组件(本来是打算考虑多行的情况的,但是css多行省略失效了,没找到原因,只能暂时放弃)。

参考:Element table

原理

table-body.js 中可以找到这一部分的逻辑
element 表格气泡是如何实现的_第1张图片
从源码中可以看到使用了createRange 来获取宽度,这东西还真没听说过,百度查了一下,基本用法如下:

Document.createRange()

会返回一个范围对象,该对象里有两个函数

Range.setStart()

设置范围对象的开始位置,如果起始节点类型是 Text、Comment 或 CDATASection之一,那么 startOffset 指的是从起始节点算起字符的偏移量。 对于其他 Node 类型节点,startOffset 是指从起始结点开始算起子节点的偏移量。
该方法有两个参数:startNode,用于设定范围对象的起始位置;startOffset,必须为不小于0的整数,表示从startNode的开始位置算起的偏移量

Range.setEnd()

用于设置范围对象的结束位置,如果结束节点类型是 Text、Comment 或 CDATASection之一,那么 endOffset 指的是从结束节点算起字符的偏移量。 对于其他 Node 类型节点,endOffset 是指从结束结点开始算起子节点的偏移量。
该方法有两个参数:endNode,用于设置结束位置;endOffset,必须为不小于 0 的整数。表示从endNode的结束位置算起的偏移量。

Range.getBoundingClientRect()

返回一个 DOMRect 对象,该对象将范围中的内容包围起来;即该对象是一个将范围内所有元素的边界矩形包围起来的矩形

// 判断是否text-overflow, 如果是就显示tooltip
   const cellChild = event.target.querySelector('.cell');
   if (!(hasClass(cellChild, 'el-tooltip') && cellChild.childNodes.length)) {
     return;
   }
   // use range width instead of scrollWidth to determine whether the text is overflowing
   // to address a potential FireFox bug: https://bugzilla.mozilla.org/show_bug.cgi?id=1074543#c3
   const range = document.createRange();
   range.setStart(cellChild, 0);
   range.setEnd(cellChild, cellChild.childNodes.length);
   const rangeWidth = range.getBoundingClientRect().width;
   const padding = (parseInt(getStyle(cellChild, 'paddingLeft'), 10) || 0) +
     (parseInt(getStyle(cellChild, 'paddingRight'), 10) || 0);
   if ((rangeWidth + padding > cellChild.offsetWidth || cellChild.scrollWidth > cellChild.offsetWidth) && this.$refs.tooltip) {
     const tooltip = this.$refs.tooltip;
     // TODO 会引起整个 Table 的重新渲染,需要优化
     this.tooltipContent = cell.innerText || cell.textContent;
     tooltip.referenceElm = cell;
     tooltip.$refs.popper && (tooltip.$refs.popper.style.display = 'none');
     tooltip.doDestroy();
     tooltip.setExpectedState(true);
     this.activateTooltip(tooltip);
   }
 },

从源码中可以看出,先获取单元格对象,然后设置相应的范围;因为表格列是一个插槽,所以这里用的是range.setEnd(cellChild, cellChild.childNodes.length);
后面的逻辑就是数值相加判断是否文本溢出

demo:文本组件

demo

<template>
    <div class="container" style="height: 100px;">
        <el-input v-model="value" placeholder="请输入"></el-input>
        <my-text show-overflow-tooltip>{{ value }}</my-text>
    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import myText from './my-text.vue';
const value = ref('');
</script>
<style lang="scss" scoped>
.container {
    width: 400px;
}
</style>

组件

<template>
    <div class="my-text single-line" ref="textRef" @mouseenter="createTip" @mouseleave="removeTip">
        <slot></slot>
    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';

// 属性
const props = defineProps({
    showOverflowTooltip: {
        type: Boolean,
        default: false
    }
});

const textRef = ref();
// 创建气泡
const createTip = () => {
    // 判断气泡是否存在,是否添加了显示气泡的属性,文本是否溢出
    const hasExist = document.querySelector('.tip');
    if (!hasExist && props.showOverflowTooltip && isOverflow(textRef.value)) {
        // 文本内容
        const content = textRef.value.innerText;
        // 创建气泡
        const tip = document.createElement('div');
        tip.innerText = content;
        tip.classList.add('tip');
        // 插入到容器里
        document.body.appendChild(tip);
        tip.style.left = textRef.value.offsetLeft + 'px';
        tip.style.top = -1 * textRef.value.offsetHeight - tip.offsetHeight - 12 + 'px';
    }
};
// 删除气泡
const removeTip = () => {
    const tip = document.querySelector('.tip');
    if (tip) {
        document.body.removeChild(tip);
    }
};

// 判断文本是否溢出
const isOverflow = (cell: HTMLElement) => {
    // 创建范围对象
    const range = document.createRange();
    // 设置开始值和结束值
    range.setStart(cell, 0);
    range.setEnd(cell, cell.childNodes.length);
    // 获取范围宽度
    const rangeWidth = range.getBoundingClientRect().width;
    const computedStyle = window.getComputedStyle(cell, null);
    // 计算padding
    const padding = (parseInt(computedStyle.paddingLeft) || 0) + (parseInt(computedStyle.paddingRight) || 0);
    // 判断是否文本溢出
    return (rangeWidth + padding > cell.offsetWidth || cell.scrollWidth > cell.offsetWidth);
};
</script>

<!-- 注:因为气泡是添加的全局的,因此不能设置scoped范围 -->
<style   lang="scss">
.my-text {
    width: 100px;
    min-width: 20px;
    height: 20px;
    margin-top: 50px;
    margin-left: 400px;
    padding: 2px 5px;
    font-size: 12px;
    line-height: 20px;
    background-color: #f5f7fa;
    border: 1px solid #e9eef0;
    border-radius: 3px;
}

.single-line {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    word-break: break-all;
}

.tip {
    position: relative;
    width: max-content;
    padding: 5px;
    color: #fff;
    font-size: 10px;
    line-height: 16px;
    background-color: #303133;
    border-radius: 3px;

    &::before {
        position: absolute;
        bottom: -10px;
        left: 20%;
        width: 15px;
        height: 10px;
        background-color: #303133;
        content: "";
        clip-path: polygon(0 0, 70% 0, 10% 100%);
    }
}
</style>

效果图
element 表格气泡是如何实现的_第2张图片

你可能感兴趣的:(Element,javascript,前端,vue.js)