js实现多行内容超出省略号

lineWrap.js

/**
 * 根据传入的line显示行数,进行内容切割
 * @param {String} content 全部内容
 * @param {HTMLElement} el 临时元素用来获取真实元素大小
 * @param {ObjectConstructor} cfg 配置
 * @param {Number} line 显示的行数
 * @returns 
 */
function cutContentWithLine(content, el, cfg, line) {
    // 将全部内容赋值给隐藏元素
    el.innerhtml = content;
    // 计算内容占比
    const { percent } = computedPercent(el);
    // 截取内容得到截取后的字符数量
    const { total } = cutContent(content);
    // 计算展示字符串的长度 (所有字符数 * 展示百分比 * 展示的行数) - 
    const showLen = +(total * percent * line).toFixed(0) - cfg.placeholder;
    // 根据展示字符数, 进行字符串切割
    const { content: cutString } = cutContent(content, showLen);
    return {
        // 切割后字符串
        content: cutString,
        // 发生了切割,则返回true, 无需切割返回false
        showDot: cutString !== content
    }
}

/**
 * 从所有内容content截取展示部分的内容
 * @param {String} content 所有内容
 * @param {Number} maxLen 展示长度
 * @returns 
 */
function cutContent(content, maxLen) {
    const len = content.length
    let total = 0
    let outContent = '';
    for (let i = 0; i < len; i++) {
        if (content[i].charCodeAt() > 255) {
            // 大于255说明不是简单字符,站2个简单字符的位置
            total += 2;
        } else {
            total += 1;
        }
        // 传入了最多展示数 && 当前截取的字符数 > 最多展示数
        if (maxLen && total > maxLen) {
            break;
        }
        // 将字符拼接成展示内容
        outContent += content[i];
    }
    // 如果没有传'最多展示数' 则返回全部字符数 + 全部内容
    // 传了'最多展示数' 返回切割后展示的字符数 + 截取的内容
    return {
        total: total,
        content: outContent
    }
}

/**
 * 计算隐藏元素el(span) 判断内部的能容是否发生了滚动
 * @param {HTMLElement} el 临时元素用来获取真实元素大小
 * @returns 
 */
function computedPercent(el) {
    // 获取元素的宽度
    const offsetWidth = el.offsetWidth;
    // 获取元素的滚动宽度
    const scrollWidth = el.scrollWidth;
    // 判断是否有被隐藏的内容
    const gap = scrollWidth - offsetWidth;
    // 可展示的内容站全部内容的百分比
    const percent = Math.floor(offsetWidth / scrollWidth * 1e3) / 1e3;
    // 将状态返回出去
    return {
        // 是否展示完全
        gap: gap,
        // 展示部分站全部内容的百分比
        percent: percent
    }
}

// 当然文字展示的多少,也是和字体大小相关的,所以我们也需要把字体大小的因素考虑到,而且作为一个工作方法,本身就不应该页面中的元素有关联,所以我们应该在方法中自己创建元素,放入内容,计算offsetWidth和scrollWidth。
function cutFnFactory(opt) {
    // 配置项
    const cfg = {
        // '更多'字符
        padding: opt.padding || "...",
        // 类名
        classList: opt.classList || [],
        // 样式
        style: opt.style || {},
        debug: opt.debug
    };
    // 展示行数(默认为1)
    const line = opt.line || 1;
    // 占位符的字符个数
    cfg.placeholder = cutContent(cfg.padding).total;
    // 创建临时元素el
    const el = document.createElement("span");
    // 添加类名
    el.className = cfg.classList.join(" ");
    // 自定义样式
    const customStyles = [];
    for (const styleKey in cfg.style) {
        if (cfg.style.hasOwnProperty(styleKey)) {
            customStyles.push(styleKey + ":" + cfg.style[styleKey]);
        }
    }
    // 创建样式字符串
    el.style.cssText = "position:absolute;left:0;top:0;background:transparent;color:transparent;height:100%;white-space:nowrap;overflow:visible;border:0;" + (cfg.debug ? "background:white;color:red;" : "") + customStyles.join(";");
    // 创建一个div容器
    const div = document.createElement("div");
    // 将span添加到div中
    div.appendChild(el);
    // 设置样式
    div.style.cssText = "user-select:none;width:99%;min-height:50px;line-height:50px;position:absolute;left:3px;top:3px;overflow:hidden;outline:0;background:transparent;" + (cfg.debug ? "outline:1px solid red;background:black;" : "");
    // 在页面上添加div元素
    document.body.appendChild(div);
    // 获取span元素的样式
    const css = window.getComputedStyle(el);
    // 添加fontSize大小 (默认值为16)
    cfg.fontSize = parseFloat(css.fontSize) || 16;
    // 返回内容的处理方法
    return function(content) {
        // 将内容添加到临时span
        el.innerHTML = content;
        // 初始化结果对象默认值
        const result = {
            // 是否展示placeholder
            showDot: false,
            // 截取的字符串
            cutContent: '',
            // 全部的内容
            allContent: content
        }
        const { gap } = computedPercent(el);
        // 内容未展示完全
        if (gap > 0) {
            const { content: cutContent, showDot } = cutContentWithLine(content, el, cfg, line)
            result.cutContent = cutContent
            result.showDot = showDot
        }
        return result
    }
}

/**
 * 缓存剪切方法
 * @param {String} content 内容
 * @param {String} fontSize 文字的大小(带单位px)
 * @param {String} width 内容展示框的大小(带单位px)
 * @param {Number} line 展示行数 
 * @returns 
 */
function cacheCutStringFn(content, fontSize, width, line) {
    // 判断是否有缓存的方法
    this.cutStringFns || (this.cutStringFns = {});
    // 缓存方法的key
    const key = 'key_' + fontSize + '_' + width;
    // 创建方法
    let fn = this.cutStringFns[key];
    // 无方法,则进行缓存
    if (!fn) {
        const options = {
            style: {
                'font-size': fontSize,
                'width': width
            },
            line: line
        }
        fn = this.cutStringFns[key] = cutFnFactory(options)
    }
    // 返回cutFnFactory中return的方法
    return fn(content);
}

export default {
    cacheCutStringFn
}

TestWrap.vue

<template>
    <div class="test-line">
        <div id="wrap-box" :style="`font-size: ${fontSize}px;width: ${width}px;`">
           {{showContent}}
           <span class="dot" @click="handleExpand" v-if="showDot">...</span>
        </div>
    </div>
</template>

<script>
import LineWrap from '@/common/utils/lineWrap.js'
export default {
    name: 'TestLine',
    data () {
        return {
            // 全部内容
            content: '',
            // 展示的内容
            showContent: '',
            // 是否展示placeholder默认为省略号
            showDot: false,
            fontSize: 16,
            width: 200,
            line: 2
        }
    },
    mounted () {
        this.content = '啊啊啊啊暗暗哈哈哈哈,叽叽***叽叽叽叽叽叽哈哈!哈啦(啦啦酷%酷酷酷酷酷酷酷酷啦啦啦啦呃呃呃呃呃呃啦啦啦啦啦啦啦'
        this.fontSize = 20
        this.width = 300
        this.wrapContent()
    },
    methods: {
        wrapContent () {
            const { showDot, cutContent } = LineWrap.cacheCutStringFn(this.content, `${this.fontSize}px`, `${this.width}px`, this.line)
            this.showContent = cutContent
            this.showDot = showDot
        },
        handleExpand () {
            this.showContent = this.content
            this.showDot = false
        }
    }
}
</script>

<style lang="scss" scoped>
.test-line {
    width: 100%;
    height: 600px;
}
#wrap-box {
    width: 300px;
    background-color: #cccccc;
}
.dot {
    color: blue;
    cursor: pointer;
}
</style>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值