文本溢出截断省略

(1)单行文本溢出省略

在这里插入图片描述

<style>
    .demo {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
</style>
<body>
	<div class="demo">这是一段很长的文本</div>
</body>

(2)多行文本溢出省略

在这里插入图片描述
多行文本溢出省略(按行数)

多适用于移动端页面,因为移动设备浏览器更多是基于 WebKit 内核

<style>
	.demo {
		  display: -webkit-box;
	    overflow: hidden;
	    -webkit-line-clamp: 2;
	    -webkit-box-orient: vertical;
	}
</style>

<body>
	<div class='demo'>这是一段很长的文本</div>
</body>

基于 JavaScript 的实现方案
在这里插入图片描述

<script type="text/javascript">
    const text = '这是一段很长的文本';
    const totalTextLen = text.length;
    const formatStr = () => {
        const ele = document.getElementsByClassName('demo')[0];
        const lineNum = 2;
        const baseWidth = window.getComputedStyle(ele).width;
        const baseFontSize = window.getComputedStyle(ele).fontSize;
        const lineWidth = +baseWidth.slice(0, -2);

        // 所计算的strNum为元素内部一行可容纳的字数(不区分中英文)
        const strNum = Math.floor(lineWidth / +baseFontSize.slice(0, -2));

        let content = '';
        
      	// 多行可容纳总字数
        const totalStrNum = Math.floor(strNum * lineNum);

        const lastIndex = totalStrNum - totalTextLen;

        if (totalTextLen > totalStrNum) {
            content = text.slice(0, lastIndex - 3).concat('...');
        } else {
            content = text;
        }
        ele.innerHTML = content;
    }
    
    formatStr();
    
		window.onresize = () => {
        formatStr();
    };
</script>

<body>
	<div class='demo'></div>
</body>
发布了393 篇原创文章 · 获赞 303 · 访问量 134万+

猜你喜欢

转载自blog.csdn.net/qq_24147051/article/details/102951305
今日推荐